pi-wasm-kit 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/NOTICE +11 -0
- package/README.md +206 -2
- package/dist/engine.d.ts +30 -0
- package/dist/engine.js +246 -0
- package/dist/guest/bridge.d.ts +1 -0
- package/dist/guest/bridge.js +14 -0
- package/dist/guest/entry.d.ts +1 -0
- package/dist/guest/entry.js +134 -0
- package/dist/guest/journal.d.ts +6 -0
- package/dist/guest/journal.js +21 -0
- package/dist/guest/platform.d.ts +1 -0
- package/dist/guest/platform.js +64 -0
- package/dist/guest-meta.json +1 -0
- package/dist/guest-source.d.ts +2 -0
- package/dist/guest-source.js +3 -0
- package/dist/guest.js +21929 -0
- package/dist/index.d.ts +104 -0
- package/dist/index.js +84 -0
- package/dist/licenses/@earendil-works__chord__LICENSE +21 -0
- package/dist/licenses/@earendil-works__pi-ai__LICENSE +21 -0
- package/dist/licenses/@earendil-works__pi-durable__LICENSE +21 -0
- package/dist/licenses/@jitl__quickjs-wasmfile-release-sync__LICENSE +47 -0
- package/dist/licenses/abort-controller__LICENSE +21 -0
- package/dist/licenses/event-target-shim__LICENSE +22 -0
- package/dist/licenses/manifest.json +47 -0
- package/dist/licenses/partial-json__LICENSE +21 -0
- package/dist/licenses/quickjs-emscripten-core__LICENSE +21 -0
- package/dist/licenses/typebox__license +23 -0
- package/dist/providers/openai.d.ts +8 -0
- package/dist/providers/openai.js +41 -0
- package/dist/storage/browser.d.ts +2 -0
- package/dist/storage/browser.js +75 -0
- package/dist/storage/node.d.ts +2 -0
- package/dist/storage/node.js +105 -0
- package/dist/types.d.ts +66 -0
- package/dist/types.js +1 -0
- package/package.json +75 -4
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// Generated by scripts/build.mjs.
|
|
2
|
+
const source = "\"use strict\";\n(() => {\n var __create = Object.create;\n var __defProp = Object.defineProperty;\n var __getOwnPropDesc = Object.getOwnPropertyDescriptor;\n var __getOwnPropNames = Object.getOwnPropertyNames;\n var __getProtoOf = Object.getPrototypeOf;\n var __hasOwnProp = Object.prototype.hasOwnProperty;\n var __commonJS = (cb, mod) => function __require() {\n try {\n return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\n } catch (e) {\n throw mod = 0, e;\n }\n };\n var __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n };\n var __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n };\n var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n ));\n\n // node_modules/event-target-shim/dist/event-target-shim.js\n var require_event_target_shim = __commonJS({\n \"node_modules/event-target-shim/dist/event-target-shim.js\"(exports, module) {\n \"use strict\";\n Object.defineProperty(exports, \"__esModule\", { value: true });\n var privateData = /* @__PURE__ */ new WeakMap();\n var wrappers = /* @__PURE__ */ new WeakMap();\n function pd(event) {\n const retv = privateData.get(event);\n console.assert(\n retv != null,\n \"'this' is expected an Event object, but got\",\n event\n );\n return retv;\n }\n function setCancelFlag(data) {\n if (data.passiveListener != null) {\n if (typeof console !== \"undefined\" && typeof console.error === \"function\") {\n console.error(\n \"Unable to preventDefault inside passive event listener invocation.\",\n data.passiveListener\n );\n }\n return;\n }\n if (!data.event.cancelable) {\n return;\n }\n data.canceled = true;\n if (typeof data.event.preventDefault === \"function\") {\n data.event.preventDefault();\n }\n }\n function Event(eventTarget, event) {\n privateData.set(this, {\n eventTarget,\n event,\n eventPhase: 2,\n currentTarget: eventTarget,\n canceled: false,\n stopped: false,\n immediateStopped: false,\n passiveListener: null,\n timeStamp: event.timeStamp || Date.now()\n });\n Object.defineProperty(this, \"isTrusted\", { value: false, enumerable: true });\n const keys = Object.keys(event);\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n if (!(key in this)) {\n Object.defineProperty(this, key, defineRedirectDescriptor(key));\n }\n }\n }\n Event.prototype = {\n /**\n * The type of this event.\n * @type {string}\n */\n get type() {\n return pd(this).event.type;\n },\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get target() {\n return pd(this).eventTarget;\n },\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get currentTarget() {\n return pd(this).currentTarget;\n },\n /**\n * @returns {EventTarget[]} The composed path of this event.\n */\n composedPath() {\n const currentTarget = pd(this).currentTarget;\n if (currentTarget == null) {\n return [];\n }\n return [currentTarget];\n },\n /**\n * Constant of NONE.\n * @type {number}\n */\n get NONE() {\n return 0;\n },\n /**\n * Constant of CAPTURING_PHASE.\n * @type {number}\n */\n get CAPTURING_PHASE() {\n return 1;\n },\n /**\n * Constant of AT_TARGET.\n * @type {number}\n */\n get AT_TARGET() {\n return 2;\n },\n /**\n * Constant of BUBBLING_PHASE.\n * @type {number}\n */\n get BUBBLING_PHASE() {\n return 3;\n },\n /**\n * The target of this event.\n * @type {number}\n */\n get eventPhase() {\n return pd(this).eventPhase;\n },\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopPropagation() {\n const data = pd(this);\n data.stopped = true;\n if (typeof data.event.stopPropagation === \"function\") {\n data.event.stopPropagation();\n }\n },\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopImmediatePropagation() {\n const data = pd(this);\n data.stopped = true;\n data.immediateStopped = true;\n if (typeof data.event.stopImmediatePropagation === \"function\") {\n data.event.stopImmediatePropagation();\n }\n },\n /**\n * The flag to be bubbling.\n * @type {boolean}\n */\n get bubbles() {\n return Boolean(pd(this).event.bubbles);\n },\n /**\n * The flag to be cancelable.\n * @type {boolean}\n */\n get cancelable() {\n return Boolean(pd(this).event.cancelable);\n },\n /**\n * Cancel this event.\n * @returns {void}\n */\n preventDefault() {\n setCancelFlag(pd(this));\n },\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n */\n get defaultPrevented() {\n return pd(this).canceled;\n },\n /**\n * The flag to be composed.\n * @type {boolean}\n */\n get composed() {\n return Boolean(pd(this).event.composed);\n },\n /**\n * The unix time of this event.\n * @type {number}\n */\n get timeStamp() {\n return pd(this).timeStamp;\n },\n /**\n * The target of this event.\n * @type {EventTarget}\n * @deprecated\n */\n get srcElement() {\n return pd(this).eventTarget;\n },\n /**\n * The flag to stop event bubbling.\n * @type {boolean}\n * @deprecated\n */\n get cancelBubble() {\n return pd(this).stopped;\n },\n set cancelBubble(value) {\n if (!value) {\n return;\n }\n const data = pd(this);\n data.stopped = true;\n if (typeof data.event.cancelBubble === \"boolean\") {\n data.event.cancelBubble = true;\n }\n },\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n * @deprecated\n */\n get returnValue() {\n return !pd(this).canceled;\n },\n set returnValue(value) {\n if (!value) {\n setCancelFlag(pd(this));\n }\n },\n /**\n * Initialize this event object. But do nothing under event dispatching.\n * @param {string} type The event type.\n * @param {boolean} [bubbles=false] The flag to be possible to bubble up.\n * @param {boolean} [cancelable=false] The flag to be possible to cancel.\n * @deprecated\n */\n initEvent() {\n }\n };\n Object.defineProperty(Event.prototype, \"constructor\", {\n value: Event,\n configurable: true,\n writable: true\n });\n if (typeof window !== \"undefined\" && typeof window.Event !== \"undefined\") {\n Object.setPrototypeOf(Event.prototype, window.Event.prototype);\n wrappers.set(window.Event.prototype, Event);\n }\n function defineRedirectDescriptor(key) {\n return {\n get() {\n return pd(this).event[key];\n },\n set(value) {\n pd(this).event[key] = value;\n },\n configurable: true,\n enumerable: true\n };\n }\n function defineCallDescriptor(key) {\n return {\n value() {\n const event = pd(this).event;\n return event[key].apply(event, arguments);\n },\n configurable: true,\n enumerable: true\n };\n }\n function defineWrapper(BaseEvent, proto) {\n const keys = Object.keys(proto);\n if (keys.length === 0) {\n return BaseEvent;\n }\n function CustomEvent(eventTarget, event) {\n BaseEvent.call(this, eventTarget, event);\n }\n CustomEvent.prototype = Object.create(BaseEvent.prototype, {\n constructor: { value: CustomEvent, configurable: true, writable: true }\n });\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n if (!(key in BaseEvent.prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key);\n const isFunc = typeof descriptor.value === \"function\";\n Object.defineProperty(\n CustomEvent.prototype,\n key,\n isFunc ? defineCallDescriptor(key) : defineRedirectDescriptor(key)\n );\n }\n }\n return CustomEvent;\n }\n function getWrapper(proto) {\n if (proto == null || proto === Object.prototype) {\n return Event;\n }\n let wrapper = wrappers.get(proto);\n if (wrapper == null) {\n wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto);\n wrappers.set(proto, wrapper);\n }\n return wrapper;\n }\n function wrapEvent(eventTarget, event) {\n const Wrapper = getWrapper(Object.getPrototypeOf(event));\n return new Wrapper(eventTarget, event);\n }\n function isStopped(event) {\n return pd(event).immediateStopped;\n }\n function setEventPhase(event, eventPhase) {\n pd(event).eventPhase = eventPhase;\n }\n function setCurrentTarget(event, currentTarget) {\n pd(event).currentTarget = currentTarget;\n }\n function setPassiveListener(event, passiveListener) {\n pd(event).passiveListener = passiveListener;\n }\n var listenersMap = /* @__PURE__ */ new WeakMap();\n var CAPTURE = 1;\n var BUBBLE = 2;\n var ATTRIBUTE = 3;\n function isObject(x) {\n return x !== null && typeof x === \"object\";\n }\n function getListeners(eventTarget) {\n const listeners = listenersMap.get(eventTarget);\n if (listeners == null) {\n throw new TypeError(\n \"'this' is expected an EventTarget object, but got another value.\"\n );\n }\n return listeners;\n }\n function defineEventAttributeDescriptor(eventName) {\n return {\n get() {\n const listeners = getListeners(this);\n let node = listeners.get(eventName);\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n return node.listener;\n }\n node = node.next;\n }\n return null;\n },\n set(listener) {\n if (typeof listener !== \"function\" && !isObject(listener)) {\n listener = null;\n }\n const listeners = getListeners(this);\n let prev = null;\n let node = listeners.get(eventName);\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n if (prev !== null) {\n prev.next = node.next;\n } else if (node.next !== null) {\n listeners.set(eventName, node.next);\n } else {\n listeners.delete(eventName);\n }\n } else {\n prev = node;\n }\n node = node.next;\n }\n if (listener !== null) {\n const newNode = {\n listener,\n listenerType: ATTRIBUTE,\n passive: false,\n once: false,\n next: null\n };\n if (prev === null) {\n listeners.set(eventName, newNode);\n } else {\n prev.next = newNode;\n }\n }\n },\n configurable: true,\n enumerable: true\n };\n }\n function defineEventAttribute2(eventTargetPrototype, eventName) {\n Object.defineProperty(\n eventTargetPrototype,\n `on${eventName}`,\n defineEventAttributeDescriptor(eventName)\n );\n }\n function defineCustomEventTarget(eventNames) {\n function CustomEventTarget() {\n EventTarget2.call(this);\n }\n CustomEventTarget.prototype = Object.create(EventTarget2.prototype, {\n constructor: {\n value: CustomEventTarget,\n configurable: true,\n writable: true\n }\n });\n for (let i = 0; i < eventNames.length; ++i) {\n defineEventAttribute2(CustomEventTarget.prototype, eventNames[i]);\n }\n return CustomEventTarget;\n }\n function EventTarget2() {\n if (this instanceof EventTarget2) {\n listenersMap.set(this, /* @__PURE__ */ new Map());\n return;\n }\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(arguments[0]);\n }\n if (arguments.length > 0) {\n const types = new Array(arguments.length);\n for (let i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i];\n }\n return defineCustomEventTarget(types);\n }\n throw new TypeError(\"Cannot call a class as a function\");\n }\n EventTarget2.prototype = {\n /**\n * Add a given listener to this event target.\n * @param {string} eventName The event name to add.\n * @param {Function} listener The listener to add.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n addEventListener(eventName, listener, options) {\n if (listener == null) {\n return;\n }\n if (typeof listener !== \"function\" && !isObject(listener)) {\n throw new TypeError(\"'listener' should be a function or an object.\");\n }\n const listeners = getListeners(this);\n const optionsIsObj = isObject(options);\n const capture = optionsIsObj ? Boolean(options.capture) : Boolean(options);\n const listenerType = capture ? CAPTURE : BUBBLE;\n const newNode = {\n listener,\n listenerType,\n passive: optionsIsObj && Boolean(options.passive),\n once: optionsIsObj && Boolean(options.once),\n next: null\n };\n let node = listeners.get(eventName);\n if (node === void 0) {\n listeners.set(eventName, newNode);\n return;\n }\n let prev = null;\n while (node != null) {\n if (node.listener === listener && node.listenerType === listenerType) {\n return;\n }\n prev = node;\n node = node.next;\n }\n prev.next = newNode;\n },\n /**\n * Remove a given listener from this event target.\n * @param {string} eventName The event name to remove.\n * @param {Function} listener The listener to remove.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n removeEventListener(eventName, listener, options) {\n if (listener == null) {\n return;\n }\n const listeners = getListeners(this);\n const capture = isObject(options) ? Boolean(options.capture) : Boolean(options);\n const listenerType = capture ? CAPTURE : BUBBLE;\n let prev = null;\n let node = listeners.get(eventName);\n while (node != null) {\n if (node.listener === listener && node.listenerType === listenerType) {\n if (prev !== null) {\n prev.next = node.next;\n } else if (node.next !== null) {\n listeners.set(eventName, node.next);\n } else {\n listeners.delete(eventName);\n }\n return;\n }\n prev = node;\n node = node.next;\n }\n },\n /**\n * Dispatch a given event.\n * @param {Event|{type:string}} event The event to dispatch.\n * @returns {boolean} `false` if canceled.\n */\n dispatchEvent(event) {\n if (event == null || typeof event.type !== \"string\") {\n throw new TypeError('\"event.type\" should be a string.');\n }\n const listeners = getListeners(this);\n const eventName = event.type;\n let node = listeners.get(eventName);\n if (node == null) {\n return true;\n }\n const wrappedEvent = wrapEvent(this, event);\n let prev = null;\n while (node != null) {\n if (node.once) {\n if (prev !== null) {\n prev.next = node.next;\n } else if (node.next !== null) {\n listeners.set(eventName, node.next);\n } else {\n listeners.delete(eventName);\n }\n } else {\n prev = node;\n }\n setPassiveListener(\n wrappedEvent,\n node.passive ? node.listener : null\n );\n if (typeof node.listener === \"function\") {\n try {\n node.listener.call(this, wrappedEvent);\n } catch (err) {\n if (typeof console !== \"undefined\" && typeof console.error === \"function\") {\n console.error(err);\n }\n }\n } else if (node.listenerType !== ATTRIBUTE && typeof node.listener.handleEvent === \"function\") {\n node.listener.handleEvent(wrappedEvent);\n }\n if (isStopped(wrappedEvent)) {\n break;\n }\n node = node.next;\n }\n setPassiveListener(wrappedEvent, null);\n setEventPhase(wrappedEvent, 0);\n setCurrentTarget(wrappedEvent, null);\n return !wrappedEvent.defaultPrevented;\n }\n };\n Object.defineProperty(EventTarget2.prototype, \"constructor\", {\n value: EventTarget2,\n configurable: true,\n writable: true\n });\n if (typeof window !== \"undefined\" && typeof window.EventTarget !== \"undefined\") {\n Object.setPrototypeOf(EventTarget2.prototype, window.EventTarget.prototype);\n }\n exports.defineEventAttribute = defineEventAttribute2;\n exports.EventTarget = EventTarget2;\n exports.default = EventTarget2;\n module.exports = EventTarget2;\n module.exports.EventTarget = module.exports[\"default\"] = EventTarget2;\n module.exports.defineEventAttribute = defineEventAttribute2;\n }\n });\n\n // node_modules/abort-controller/dist/abort-controller.mjs\n var import_event_target_shim = __toESM(require_event_target_shim(), 1);\n var AbortSignal2 = class extends import_event_target_shim.EventTarget {\n /**\n * AbortSignal cannot be constructed directly.\n */\n constructor() {\n super();\n throw new TypeError(\"AbortSignal cannot be constructed directly\");\n }\n /**\n * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.\n */\n get aborted() {\n const aborted = abortedFlags.get(this);\n if (typeof aborted !== \"boolean\") {\n throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? \"null\" : typeof this}`);\n }\n return aborted;\n }\n };\n (0, import_event_target_shim.defineEventAttribute)(AbortSignal2.prototype, \"abort\");\n function createAbortSignal() {\n const signal = Object.create(AbortSignal2.prototype);\n import_event_target_shim.EventTarget.call(signal);\n abortedFlags.set(signal, false);\n return signal;\n }\n function abortSignal(signal) {\n if (abortedFlags.get(signal) !== false) {\n return;\n }\n abortedFlags.set(signal, true);\n signal.dispatchEvent({ type: \"abort\" });\n }\n var abortedFlags = /* @__PURE__ */ new WeakMap();\n Object.defineProperties(AbortSignal2.prototype, {\n aborted: { enumerable: true }\n });\n if (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortSignal2.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortSignal\"\n });\n }\n var AbortController2 = class {\n /**\n * Initialize this controller.\n */\n constructor() {\n signals.set(this, createAbortSignal());\n }\n /**\n * Returns the `AbortSignal` object associated with this object.\n */\n get signal() {\n return getSignal(this);\n }\n /**\n * Abort and signal to any observers that the associated activity is to be aborted.\n */\n abort() {\n abortSignal(getSignal(this));\n }\n };\n var signals = /* @__PURE__ */ new WeakMap();\n function getSignal(controller) {\n const signal = signals.get(controller);\n if (signal == null) {\n throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? \"null\" : typeof controller}`);\n }\n return signal;\n }\n Object.defineProperties(AbortController2.prototype, {\n signal: { enumerable: true },\n abort: { enumerable: true }\n });\n if (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortController2.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortController\"\n });\n }\n\n // src/guest/platform.ts\n var abort = AbortController2.prototype.abort;\n AbortController2.prototype.abort = function(reason) {\n if (this.signal.aborted) return;\n Object.defineProperty(this.signal, \"reason\", { value: reason ?? new Error(\"Operation aborted\") });\n abort.call(this);\n };\n AbortSignal2.prototype.throwIfAborted = function() {\n if (this.aborted) throw this.reason;\n };\n AbortSignal2.any = (signals2) => {\n const controller = new AbortController2();\n const handlers = /* @__PURE__ */ new Map();\n const stop = (signal) => {\n controller.abort(signal.reason);\n for (const [source, handler] of handlers) source.removeEventListener(\"abort\", handler);\n };\n for (const signal of signals2) {\n if (signal.aborted) {\n stop(signal);\n break;\n }\n const handler = () => stop(signal);\n handlers.set(signal, handler);\n signal.addEventListener(\"abort\", handler, { once: true });\n }\n return controller.signal;\n };\n Object.assign(globalThis, {\n AbortController: AbortController2,\n AbortSignal: AbortSignal2,\n URL: class {\n href;\n constructor(input, base) {\n Object.assign(this, JSON.parse(__hostSync(\"url\", JSON.stringify([String(input), base]))));\n }\n toString() {\n return this.href;\n }\n toJSON() {\n return this.href;\n }\n static canParse(input, base) {\n try {\n __hostSync(\"url\", JSON.stringify([input, base]));\n return true;\n } catch {\n return false;\n }\n }\n },\n setTimeout: (fn, ms = 0, ...args) => __timer(() => fn(...args), ms),\n clearTimeout: __clearTimer,\n performance: { now: () => Number(__hostSync(\"now\", \"\")) },\n queueMicrotask: (fn) => Promise.resolve().then(fn),\n structuredClone: (value) => value === void 0 ? void 0 : JSON.parse(JSON.stringify(value)),\n crypto: {\n randomUUID: () => JSON.parse(__hostSync(\"uuid\", \"\")),\n getRandomValues: (array) => {\n array.set(JSON.parse(__hostSync(\"random\", String(array.length))));\n return array;\n }\n },\n TextEncoder: class {\n encode(text = \"\") {\n return Uint8Array.from(JSON.parse(__hostSync(\"encode\", text)));\n }\n },\n TextDecoder: class {\n decode(bytes = new Uint8Array()) {\n return JSON.parse(__hostSync(\"decode\", JSON.stringify(Array.from(bytes))));\n }\n },\n console: { log() {\n }, warn() {\n }, error() {\n }, assert() {\n } },\n DOMException: class extends Error {\n constructor(message, name = \"Error\") {\n super(message);\n this.name = name;\n }\n }\n });\n\n // node_modules/@earendil-works/chord/dist/context/index.js\n var context_exports = {};\n __export(context_exports, {\n BACKGROUND_CONTEXT: () => BACKGROUND_CONTEXT,\n TODO_CONTEXT: () => TODO_CONTEXT,\n awaitWithContext: () => awaitWithContext,\n createContextKey: () => createContextKey,\n withAbortSignal: () => withAbortSignal,\n withCancel: () => withCancel,\n withContextValue: () => withContextValue,\n withoutAbortSignal: () => withoutAbortSignal\n });\n var ABORT_SIGNAL_CONTEXT_KEY = Object.freeze({\n token: /* @__PURE__ */ Symbol(\"chord.abortSignal\")\n });\n var BaseContext = class {\n get abortSignal() {\n return this.value(ABORT_SIGNAL_CONTEXT_KEY);\n }\n };\n var EmptyContext = class extends BaseContext {\n #name;\n constructor(name) {\n super();\n this.#name = name;\n }\n value(_key) {\n return void 0;\n }\n toString() {\n return this.#name;\n }\n };\n var ContextValue = class extends BaseContext {\n #parent;\n #key;\n #value;\n constructor(parent, key, value) {\n super();\n this.#parent = parent;\n this.#key = key;\n this.#value = value;\n }\n value(key) {\n if (key.token === this.#key.token)\n return this.#value;\n return this.#parent.value(key);\n }\n toString() {\n return `${this.#parent}.WithValue(${this.#key.token.description ?? \"anonymous\"})`;\n }\n };\n var BACKGROUND_CONTEXT = new EmptyContext(\"[Context BACKGROUND_CONTEXT]\");\n var TODO_CONTEXT = new EmptyContext(\"[Context TODO_CONTEXT]\");\n function createContextKey(description) {\n return Object.freeze({ token: Symbol(description) });\n }\n function withContextValue(key, value, parent) {\n return new ContextValue(parent, key, value);\n }\n function withAbortSignal(signal, context2) {\n const parentSignal = context2.abortSignal;\n const combined = parentSignal === void 0 ? signal : AbortSignal.any([parentSignal, signal]);\n return withContextValue(ABORT_SIGNAL_CONTEXT_KEY, combined, context2);\n }\n function withoutAbortSignal(context2) {\n return withContextValue(ABORT_SIGNAL_CONTEXT_KEY, void 0, context2);\n }\n function withCancel(context2) {\n const controller = new AbortController();\n return {\n context: withAbortSignal(controller.signal, context2),\n cancel: (reason) => controller.abort(reason)\n };\n }\n function awaitWithContext(promise, context2) {\n const signal = context2.abortSignal;\n if (signal === void 0)\n return promise;\n if (signal.aborted)\n return Promise.reject(abortError(signal));\n return new Promise((resolve2, reject) => {\n const onAbort = () => reject(abortError(signal));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n void promise.then((value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve2(value);\n }, (error) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n });\n });\n }\n function abortError(signal) {\n const reason = signal.reason;\n return reason instanceof Error ? reason : new DOMException(\"The operation was aborted\", \"AbortError\");\n }\n\n // node_modules/@earendil-works/pi-durable/dist/index.js\n var dist_exports = {};\n __export(dist_exports, {\n AgentDoc: () => AgentDoc,\n AssistantEntry: () => AssistantEntry,\n CompactionEntry: () => CompactionEntry,\n CompactionTask: () => CompactionTask,\n ConversationBusy: () => ConversationBusy,\n DEFAULT_COMPACTION_POLICY: () => DEFAULT_COMPACTION_POLICY,\n DEFAULT_PROGRESS_POLICY: () => DEFAULT_PROGRESS_POLICY,\n DEFAULT_RETRY_POLICY: () => DEFAULT_RETRY_POLICY,\n GenerationTask: () => GenerationTask,\n Harness: () => Harness,\n InboxDoc: () => InboxDoc,\n LiveDoc: () => LiveDoc,\n MemoryStorage: () => MemoryStorage,\n ProviderDoc: () => ProviderDoc,\n ROOT_CONVERSATION_ID: () => ROOT_CONVERSATION_ID,\n ReadAfterWrite: () => ReadAfterWrite,\n ResetEntry: () => ResetEntry,\n StorageRejected: () => StorageRejected,\n SystemEntry: () => SystemEntry,\n ToolResultEntry: () => ToolResultEntry,\n ToolTask: () => ToolTask,\n UsageDoc: () => UsageDoc,\n UserEntry: () => UserEntry,\n configure: () => configure,\n createRegistry: () => createRegistry,\n createSession: () => createSession,\n defineDoc: () => defineDoc,\n defineDocFamily: () => defineDocFamily,\n defineEntry: () => defineEntry,\n defineExtension: () => defineExtension,\n defineTask: () => defineTask,\n defineTool: () => defineTool,\n hook: () => hook,\n section: () => section,\n watchEvents: () => watchEvents,\n wrapSection: () => wrapSection,\n wrapTool: () => wrapTool\n });\n\n // node_modules/@earendil-works/chord/dist/json.js\n var DATA_DESCRIPTOR = {\n value: void 0,\n writable: true,\n enumerable: true,\n configurable: true\n };\n function copyJson(value, options) {\n return copy(value, void 0, options?.omitUndefinedProperties === true);\n }\n function copy(value, ancestors, omitUndefinedProperties) {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\")\n return value;\n if (typeof value === \"number\") {\n if (Number.isFinite(value))\n return value;\n throw new TypeError(\"Value contains a non-finite number and is not strict JSON\");\n }\n if (typeof value !== \"object\")\n throw new TypeError(`Value contains a non-JSON ${typeof value}; expected strict JSON`);\n const active = ancestors ?? /* @__PURE__ */ new Set();\n if (active.has(value))\n throw new TypeError(\"Value contains cycles and is not strict JSON\");\n active.add(value);\n try {\n if (Array.isArray(value)) {\n if (Object.getPrototypeOf(value) !== Array.prototype || Reflect.ownKeys(value).length !== value.length + 1) {\n throw new TypeError(\"Value must contain strict JSON dense plain arrays\");\n }\n const result2 = new Array(value.length);\n for (let index3 = 0; index3 < value.length; index3++) {\n const descriptor = Object.getOwnPropertyDescriptor(value, index3);\n if (descriptor === void 0 || !descriptor.enumerable || !(\"value\" in descriptor)) {\n throw new TypeError(\"Value must contain strict JSON enumerable indexed data properties\");\n }\n defineData(result2, String(index3), copy(descriptor.value, active, omitUndefinedProperties));\n }\n return result2;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError(\"Value must contain strict JSON plain objects or arrays\");\n }\n const result = Object.create(prototype);\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key === \"symbol\")\n throw new TypeError(\"Value contains a symbol key and is not strict JSON\");\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor.enumerable || !(\"value\" in descriptor)) {\n throw new TypeError(\"Value must contain strict JSON enumerable data properties\");\n }\n if (descriptor.value === void 0 && omitUndefinedProperties)\n continue;\n defineData(result, key, copy(descriptor.value, active, omitUndefinedProperties));\n }\n return result;\n } finally {\n active.delete(value);\n }\n }\n function defineData(target, key, value) {\n DATA_DESCRIPTOR.value = value;\n Object.defineProperty(target, key, DATA_DESCRIPTOR);\n DATA_DESCRIPTOR.value = void 0;\n }\n\n // node_modules/@earendil-works/chord/dist/delta/apply-immutable-trusted.js\n var DATA_DESCRIPTOR2 = {\n value: void 0,\n writable: true,\n enumerable: true,\n configurable: true\n };\n function applyImmutableTrusted(target, operations) {\n let root2 = target;\n const owned = /* @__PURE__ */ new WeakSet();\n for (const operation of operations) {\n if (operation[0] === \"r\") {\n root2 = operation[1];\n continue;\n }\n if (operation[0] === \"p\" || operation[0] === \"m\") {\n const copied2 = copyPath(root2, operation[1], operation[1].length, owned);\n root2 = copied2.root;\n if (!Array.isArray(copied2.target))\n throw new TypeError(\"Trusted array operation target is not an array\");\n if (operation[0] === \"p\")\n spliceTrusted(copied2.target, operation[2], operation[3], operation[4]);\n else\n permuteTrusted(copied2.target, operation[2]);\n continue;\n }\n const path = operation[1];\n const copied = copyPath(root2, path, path.length - 1, owned);\n root2 = copied.root;\n const key = path[path.length - 1];\n switch (operation[0]) {\n case \"s\":\n defineData2(copied.target, key, operation[2]);\n break;\n case \"d\":\n if (Array.isArray(copied.target)) {\n if (typeof key !== \"number\")\n throw new TypeError(\"Trusted array deletion key is not numeric\");\n spliceTrusted(copied.target, key, 1, []);\n } else\n Reflect.deleteProperty(copied.target, key);\n break;\n case \"a\": {\n const current = read(copied.target, key);\n if (typeof current !== \"string\")\n throw new TypeError(\"Trusted append target is not a string\");\n defineData2(copied.target, key, `${current}${operation[2]}`);\n break;\n }\n case \"t\": {\n const current = read(copied.target, key);\n if (typeof current !== \"string\")\n throw new TypeError(\"Trusted truncate target is not a string\");\n defineData2(copied.target, key, current.slice(operation[2]));\n break;\n }\n }\n }\n return root2;\n }\n function copyPath(root2, path, length, owned) {\n if (!isContainer(root2))\n throw new TypeError(\"Trusted operation root is not a container\");\n let copiedRoot = root2;\n if (!owned.has(root2)) {\n copiedRoot = shallowCopy(root2);\n owned.add(copiedRoot);\n }\n let destination = copiedRoot;\n for (let index3 = 0; index3 < length; index3++) {\n const segment = path[index3];\n const child = read(destination, segment);\n if (!isContainer(child))\n throw new TypeError(\"Trusted operation path is not a container\");\n if (owned.has(child)) {\n destination = child;\n continue;\n }\n const copy2 = shallowCopy(child);\n defineData2(destination, segment, copy2);\n owned.add(copy2);\n destination = copy2;\n }\n return { root: copiedRoot, target: destination };\n }\n function shallowCopy(value) {\n if (Array.isArray(value))\n return Array.from(value);\n const result = Object.create(Object.getPrototypeOf(value) === null ? null : Object.prototype);\n for (const key of Object.keys(value))\n defineData2(result, key, value[key]);\n return result;\n }\n function read(target, key) {\n return target[key];\n }\n function defineData2(target, key, value) {\n DATA_DESCRIPTOR2.value = value;\n Object.defineProperty(target, key, DATA_DESCRIPTOR2);\n DATA_DESCRIPTOR2.value = void 0;\n }\n function spliceTrusted(target, start, remove, items) {\n const oldLength = target.length;\n const delta = items.length - remove;\n if (delta > 0) {\n target.length = oldLength + delta;\n target.copyWithin(start + items.length, start + remove, oldLength);\n } else if (delta < 0) {\n target.copyWithin(start + items.length, start + remove, oldLength);\n target.length = oldLength + delta;\n }\n for (let index3 = 0; index3 < items.length; index3++)\n defineData2(target, start + index3, items[index3]);\n }\n function permuteTrusted(target, permutation) {\n if (target.length !== permutation.length)\n throw new TypeError(\"Trusted permutation length mismatch\");\n const previous = target.slice();\n for (let index3 = 0; index3 < permutation.length; index3++)\n target[index3] = previous[permutation[index3]];\n }\n function isContainer(value) {\n return value !== null && typeof value === \"object\";\n }\n\n // node_modules/@earendil-works/chord/dist/delta/tracker.js\n var NODE = /* @__PURE__ */ Symbol(\"chord.delta.overlay.node\");\n var PREPARED = /* @__PURE__ */ new WeakMap();\n var RELEASED = {};\n var ARRAY_MUTATORS = /* @__PURE__ */ new Set([\n \"push\",\n \"pop\",\n \"shift\",\n \"unshift\",\n \"splice\",\n \"reverse\",\n \"sort\",\n \"fill\",\n \"copyWithin\"\n ]);\n var MAX_DELTA_OPERATIONS = 4096;\n var MAX_SIMPLE_OBJECT_NODES = 128;\n var DATA_DESCRIPTOR3 = {\n value: void 0,\n writable: true,\n enumerable: true,\n configurable: true\n };\n var PreparedImpl = class {\n #context;\n value;\n base;\n ops;\n constructor(context2, value, operations) {\n this.#context = context2;\n this.value = value;\n this.base = context2.baseValue;\n this.ops = operations;\n PREPARED.set(this, context2);\n }\n get baseRevision() {\n return this.#context.baseRevision;\n }\n abort() {\n abortContext(this.#context);\n }\n };\n var ChangeImpl = class {\n #context;\n #preparedStatus;\n #settled = false;\n constructor(context2) {\n this.#context = context2;\n }\n get state() {\n const state2 = this.#context?.root?.proxy;\n if (state2 === void 0)\n throw new TypeError(\"Cannot use a settled overlay\");\n return state2;\n }\n prepare() {\n if (this.#settled)\n throw new Error(\"Change has already been settled\");\n const context2 = this.#context;\n assertWritable(context2);\n context2.status.value = \"prepared\";\n try {\n if (!context2.replacement)\n context2.ops = context2.dirty.length === 0 ? [] : emitOperations(context2);\n const prepared = materializePrepared(context2);\n this.#preparedStatus = context2.status;\n this.#settled = true;\n return prepared;\n } catch (error) {\n context2.status.value = \"aborted\";\n clearContext(context2);\n this.#settled = true;\n throw error;\n } finally {\n this.#context = void 0;\n }\n }\n abort() {\n if (this.#settled) {\n if (this.#preparedStatus?.value === \"prepared\")\n this.#preparedStatus.value = \"aborted\";\n this.#preparedStatus = void 0;\n return;\n }\n this.#settled = true;\n abortContext(this.#context);\n this.#context = void 0;\n }\n };\n var TrackerImpl = class {\n #owner = {};\n #contexts = /* @__PURE__ */ new Set();\n #selfRef;\n #value;\n #revision = 0;\n #pruneBudget = 256;\n constructor(initial) {\n this.#value = initial;\n this.#selfRef = new WeakRef(this);\n }\n get value() {\n return this.#value;\n }\n get revision() {\n return this.#revision;\n }\n beginChange() {\n const context2 = createContext(this.#selfRef, this.#owner, this.#revision, this.#value, false, this.#value);\n this.#register(context2);\n return new ChangeImpl(context2);\n }\n prepareReplace(value) {\n const context2 = createContext(this.#selfRef, this.#owner, this.#revision, value, true, this.#value);\n context2.status.value = \"prepared\";\n this.#register(context2);\n try {\n return materializePrepared(context2);\n } catch (error) {\n context2.status.value = \"aborted\";\n clearContext(context2);\n throw error;\n }\n }\n adopt(prepared) {\n const context2 = PREPARED.get(prepared);\n if (context2?.owner !== this.#owner)\n throw new Error(\"Prepared change belongs to a different tracker\");\n if (context2.status.value === \"consumed\")\n throw new Error(\"Prepared change has already been used\");\n if (context2.status.value === \"aborted\")\n throw new Error(\"Prepared change has been aborted\");\n if (context2.status.value === \"stale\")\n throw new Error(\"Prepared change is stale\");\n if (context2.status.value !== \"prepared\")\n throw new Error(\"Prepared change is not ready\");\n if (context2.baseRevision !== this.#revision) {\n context2.status.value = \"stale\";\n clearContext(context2);\n throw new Error(\"Prepared change is stale\");\n }\n if (this.#value !== prepared.base) {\n context2.status.value = \"stale\";\n throw new Error(\"Prepared change is stale\");\n }\n this.#value = prepared.value;\n context2.status.value = \"consumed\";\n this.#revision += 1;\n this.#invalidate(context2);\n }\n releaseContext(context2) {\n if (context2.registryRef !== void 0)\n this.#contexts.delete(context2.registryRef);\n context2.registryRef = void 0;\n }\n #register(context2) {\n const reference = new WeakRef(context2);\n context2.registryRef = reference;\n this.#contexts.add(reference);\n this.#pruneBudget -= 1;\n if (this.#pruneBudget === 0) {\n this.#prune();\n this.#pruneBudget = Math.max(256, this.#contexts.size);\n }\n }\n #prune() {\n for (const reference of this.#contexts) {\n if (reference.deref() === void 0)\n this.#contexts.delete(reference);\n }\n }\n #invalidate(winner) {\n for (const reference of this.#contexts) {\n const context2 = reference.deref();\n if (context2 === void 0 || context2 === winner)\n continue;\n if (context2.status.value === \"open\" || context2.status.value === \"prepared\")\n context2.status.value = \"stale\";\n releaseOverlayReferences(context2);\n }\n this.#contexts.clear();\n this.#pruneBudget = 256;\n }\n replacementBase(context2) {\n return context2.baseRevision === this.#revision ? this.#value : void 0;\n }\n };\n function track(initial) {\n return new TrackerImpl(initial);\n }\n function materializePrepared(context2) {\n const operations = ensureOperations(context2);\n const base = context2.baseValue;\n const value = operations.length === 0 ? base : context2.simpleObjectMaterialization ? cloneNode(context2.root) : materializeOperations(base, operations);\n const prepared = new PreparedImpl(context2, value, operations);\n if (context2.nodes.length > 4096)\n releaseOverlayReferences(context2);\n else\n clearContext(context2);\n return prepared;\n }\n function materializeOperations(base, operations) {\n for (const operation of operations) {\n if (operation[0] === \"p\" || operation[0] === \"m\")\n return applyImmutable(base, operations);\n }\n return applyImmutableTrusted(base, operations);\n }\n function createContext(tracker, owner, baseRevision, root2, replacement, base) {\n const context2 = {\n owner,\n tracker,\n baseRevision,\n status: { value: \"open\" },\n root: void 0,\n bases: [],\n stored: [],\n dirty: [],\n nodes: [],\n rawNodes: /* @__PURE__ */ new WeakMap(),\n ops: void 0,\n replacement,\n replacementNoop: false,\n baseValue: base,\n overlayReleased: false,\n simpleObjectMaterialization: false,\n registryRef: void 0\n };\n context2.root = createNode(context2, root2, void 0);\n return context2;\n }\n var sharedObjectHandler = {\n deleteProperty(target, property) {\n return deleteProperty(nodeForTarget(target), property);\n },\n defineProperty(target) {\n assertWritable(nodeForTarget(target).context);\n throw new TypeError(\"Defining overlay properties is not supported\");\n },\n get(target, property) {\n if (property === \"then\") {\n const node2 = target[NODE];\n if (node2 === void 0 || isSettledContext(node2.context))\n return void 0;\n }\n const node = nodeForTarget(target);\n if (property === NODE)\n return node;\n return getProperty(node, property);\n },\n getOwnPropertyDescriptor(target, property) {\n return getDescriptor(nodeForTarget(target), property);\n },\n getPrototypeOf(target) {\n const node = nodeForTarget(target);\n assertReadable(node.context);\n return Object.getPrototypeOf(nodeBase(node));\n },\n has(target, property) {\n return hasProperty(nodeForTarget(target), property);\n },\n isExtensible(target) {\n assertReadable(nodeForTarget(target).context);\n return true;\n },\n ownKeys(target) {\n return ownKeys(nodeForTarget(target));\n },\n preventExtensions(target) {\n assertWritable(nodeForTarget(target).context);\n throw new TypeError(\"Overlays cannot be made non-extensible\");\n },\n set(target, property, value) {\n return setProperty(nodeForTarget(target), property, value);\n },\n setPrototypeOf(target) {\n assertWritable(nodeForTarget(target).context);\n throw new TypeError(\"Changing an overlay prototype is not supported\");\n }\n };\n var sharedArrayHandler = sharedObjectHandler;\n function createNode(context2, base, parent, parentKind = 0, parentKey = \"\", parentSource = void 0, parentPlacement = false) {\n const existing = context2.rawNodes.get(base);\n if (existing !== void 0)\n return existing;\n const target = Array.isArray(base) ? [] : {};\n const baseIndex = context2.bases.length;\n const parentIndex = parent?.baseIndex ?? -1;\n context2.bases.push(base);\n const node = {\n context: context2,\n baseIndex,\n parentIndex,\n parentKind,\n parentKey,\n parentPlacement,\n target,\n proxy: target\n };\n if (parentSource !== void 0)\n node.parentSource = parentSource;\n target[NODE] = node;\n node.proxy = new Proxy(target, Array.isArray(base) ? sharedArrayHandler : sharedObjectHandler);\n context2.rawNodes.set(base, node);\n context2.nodes.push(node);\n return node;\n }\n function nodeBase(node) {\n return node.context.bases[node.baseIndex];\n }\n function nodeParent(node) {\n return node.parentIndex < 0 ? void 0 : node.context.nodes[node.parentIndex];\n }\n function storeValue(context2, value) {\n if (!isContainer2(value))\n return value;\n const index3 = context2.stored.length;\n context2.stored.push(value);\n return { index: index3 };\n }\n function storedValue(context2, reference) {\n return typeof reference === \"object\" && reference !== null ? context2.stored[reference.index] : reference;\n }\n function replaceStoredValue(context2, reference, value) {\n if (isContainer2(value)) {\n if (typeof reference === \"object\" && reference !== null) {\n context2.stored[reference.index] = value;\n return reference;\n }\n return storeValue(context2, value);\n }\n if (typeof reference === \"object\" && reference !== null)\n context2.stored[reference.index] = RELEASED;\n return value;\n }\n function releaseStoredValue(context2, reference) {\n if (typeof reference === \"object\" && reference !== null)\n context2.stored[reference.index] = RELEASED;\n }\n function nodeForTarget(target) {\n const node = target[NODE];\n if (node === void 0)\n throw new TypeError(\"Cannot use a settled overlay\");\n return node;\n }\n function isSettledContext(context2) {\n return context2.overlayReleased || context2.status.value === \"consumed\" || context2.status.value === \"aborted\" || context2.status.value === \"stale\";\n }\n function assertReadable(context2) {\n if (isSettledContext(context2))\n throw new TypeError(\"Cannot use a settled overlay\");\n }\n function assertWritable(context2) {\n assertReadable(context2);\n if (context2.status.value !== \"open\")\n throw new TypeError(\"Prepared overlays are read-only\");\n }\n function getProperty(node, property) {\n assertReadable(node.context);\n if (Array.isArray(nodeBase(node))) {\n const overlay = arrayOverlay(node);\n if (property === \"length\")\n return arrayLength(overlay);\n if (ARRAY_MUTATORS.has(property))\n return arrayMutators[property];\n const index3 = arrayIndex(property);\n if (index3 !== void 0)\n return getArrayIndex(node, index3);\n return Reflect.get(Array.prototype, property, node.proxy);\n }\n if (typeof property === \"symbol\")\n return Reflect.get(nodeBase(node), property, node.proxy);\n const key = String(property);\n if (!objectHas(node, key)) {\n if (isObjectDeleted(node, key) || Object.hasOwn(nodeBase(node), key))\n return void 0;\n return Reflect.get(nodeBase(node), property, node.proxy);\n }\n const value = objectValue(node, key);\n if (!isContainer2(value))\n return value;\n return createNode(node.context, value, node, 0, key, void 0, hasObjectWrite(node, key)).proxy;\n }\n function getArrayIndex(node, index3) {\n const overlay = arrayOverlay(node);\n if (index3 >= arrayLength(overlay))\n return void 0;\n const piece = locatePiece(overlay, index3);\n const sourceIndex = piece.start + piece.step * overlay.locatedOffset;\n const value = entryValueAt(node, piece, sourceIndex);\n if (!isContainer2(value))\n return value;\n return createNode(node.context, value, node, piece.kind === \"base\" ? 1 : 2, sourceIndex, piece.kind === \"insert\" ? piece.source : void 0, piece.kind === \"insert\" || hasEntryOverrideAt(overlay, piece, sourceIndex)).proxy;\n }\n function setProperty(node, property, supplied) {\n assertWritable(node.context);\n if (typeof property === \"symbol\")\n throw new TypeError(\"Symbol writes are not supported\");\n if (Array.isArray(nodeBase(node))) {\n if (property === \"length\") {\n setArrayLength(node, toArrayLength(supplied));\n return true;\n }\n const index3 = arrayIndex(property);\n if (index3 === void 0)\n throw new TypeError(\"Only array indices and length can be written\");\n if (index3 > arrayLength(arrayOverlay(node)))\n throw new TypeError(\"Overlay arrays cannot contain holes\");\n setArrayIndex(node, index3, clonePlacement(supplied));\n return true;\n }\n const key = String(property);\n if (supplied === void 0)\n return deleteProperty(node, key);\n const stored = clonePlacement(supplied);\n const current = objectValue(node, key);\n const wasDeleted = isObjectDeleted(node, key);\n if (!wasDeleted && !isContainer2(stored) && current === stored)\n return true;\n setObjectWrite(node, key, stored);\n if (wasDeleted && Object.hasOwn(nodeBase(node), key)) {\n if (node.readded === void 0)\n node.readded = /* @__PURE__ */ new Set();\n node.readded.add(key);\n }\n deleteObjectDeletion(node, key);\n markDirty(node);\n return true;\n }\n function deleteProperty(node, property) {\n assertWritable(node.context);\n if (typeof property === \"symbol\")\n throw new TypeError(\"Symbol writes are not supported\");\n if (Array.isArray(nodeBase(node)))\n throw new TypeError(\"Overlay arrays cannot contain holes\");\n const key = String(property);\n if (!objectHas(node, key))\n return true;\n deleteObjectWrite(node, key);\n node.readded?.delete(key);\n setObjectDeletion(node, key);\n markDirty(node);\n return true;\n }\n function hasProperty(node, property) {\n assertReadable(node.context);\n if (Array.isArray(nodeBase(node))) {\n if (property === \"length\")\n return true;\n const index3 = arrayIndex(property);\n if (index3 !== void 0)\n return index3 < arrayLength(arrayOverlay(node));\n return property in Array.prototype;\n }\n return typeof property === \"symbol\" ? property in nodeBase(node) : objectHas(node, String(property));\n }\n function ownKeys(node) {\n assertReadable(node.context);\n if (Array.isArray(nodeBase(node))) {\n const length = arrayLength(arrayOverlay(node));\n const keys2 = new Array(length + 1);\n for (let index3 = 0; index3 < length; index3++)\n keys2[index3] = String(index3);\n keys2[length] = \"length\";\n return keys2;\n }\n let existingKeysOnly = node.deleteKey === void 0 && node.deletes === void 0 && node.readded === void 0 && (node.writeKey === void 0 || Object.hasOwn(nodeBase(node), node.writeKey));\n if (existingKeysOnly && node.writes !== void 0) {\n for (const key of node.writes.keys()) {\n if (!Object.hasOwn(nodeBase(node), key)) {\n existingKeysOnly = false;\n break;\n }\n }\n }\n if (existingKeysOnly)\n return Object.keys(nodeBase(node));\n const keys = Object.keys(nodeBase(node)).filter((key) => !isObjectDeleted(node, key) && !node.readded?.has(key));\n const seen = new Set(keys);\n if (node.writeKey !== void 0 && !seen.has(node.writeKey)) {\n keys.push(node.writeKey);\n seen.add(node.writeKey);\n }\n if (node.writes !== void 0) {\n for (const key of node.writes.keys()) {\n if (seen.has(key))\n continue;\n keys.push(key);\n seen.add(key);\n }\n }\n const indices = [];\n const strings = [];\n for (const key of keys) {\n const index3 = arrayIndex(key);\n if (index3 === void 0)\n strings.push(key);\n else\n indices.push(index3);\n }\n indices.sort((left, right) => left - right);\n return [...indices.map(String), ...strings];\n }\n function getDescriptor(node, property) {\n assertReadable(node.context);\n if (Array.isArray(nodeBase(node))) {\n if (property === \"length\") {\n const length = arrayLength(arrayOverlay(node));\n node.target.length = length;\n return Reflect.getOwnPropertyDescriptor(node.target, \"length\");\n }\n const index3 = arrayIndex(property);\n if (index3 === void 0 || index3 >= arrayLength(arrayOverlay(node)))\n return void 0;\n } else {\n if (typeof property === \"symbol\" || !objectHas(node, String(property)))\n return void 0;\n }\n return {\n configurable: true,\n enumerable: true,\n writable: node.context.status.value === \"open\",\n value: getProperty(node, property)\n };\n }\n function hasObjectWrite(node, key) {\n return node.writeKey === key || (node.writes?.has(key) ?? false);\n }\n function setObjectWrite(node, key, value) {\n if (node.writes !== void 0) {\n const reference = node.writes.get(key);\n node.writes.set(key, reference === void 0 ? storeValue(node.context, value) : replaceStoredValue(node.context, reference, value));\n return;\n }\n if (node.writeKey === void 0 || node.writeKey === key) {\n node.writeKey = key;\n node.writeValue = node.writeValue === void 0 ? storeValue(node.context, value) : replaceStoredValue(node.context, node.writeValue, value);\n return;\n }\n node.writes = /* @__PURE__ */ new Map();\n node.writes.set(node.writeKey, node.writeValue);\n node.writes.set(key, storeValue(node.context, value));\n node.writeKey = void 0;\n node.writeValue = void 0;\n }\n function deleteObjectWrite(node, key) {\n if (node.writeKey === key) {\n node.writeKey = void 0;\n releaseStoredValue(node.context, node.writeValue);\n node.writeValue = void 0;\n } else {\n const reference = node.writes?.get(key);\n if (reference !== void 0)\n releaseStoredValue(node.context, reference);\n node.writes?.delete(key);\n }\n }\n function isObjectDeleted(node, key) {\n return node.deleteKey === key || (node.deletes?.has(key) ?? false);\n }\n function setObjectDeletion(node, key) {\n if (node.deletes !== void 0) {\n node.deletes.add(key);\n return;\n }\n if (node.deleteKey === void 0 || node.deleteKey === key) {\n node.deleteKey = key;\n return;\n }\n node.deletes = /* @__PURE__ */ new Set();\n node.deletes.add(node.deleteKey);\n node.deletes.add(key);\n node.deleteKey = void 0;\n }\n function deleteObjectDeletion(node, key) {\n if (node.deleteKey === key)\n node.deleteKey = void 0;\n else\n node.deletes?.delete(key);\n }\n function objectHas(node, key) {\n if (isObjectDeleted(node, key))\n return false;\n return hasObjectWrite(node, key) || Object.hasOwn(nodeBase(node), key);\n }\n function objectValue(node, key) {\n if (node.writeKey === key)\n return storedValue(node.context, node.writeValue);\n const reference = node.writes?.get(key);\n if (reference !== void 0)\n return storedValue(node.context, reference);\n return nodeBase(node)[key];\n }\n function markDirty(node) {\n if (node.dirty)\n return;\n node.dirty = true;\n node.context.dirty.push(node);\n for (let parent = nodeParent(node); parent !== void 0; parent = nodeParent(parent))\n parent.subtreeDirty = true;\n }\n function arrayOverlay(node) {\n if (node.array !== void 0)\n return node.array;\n const base = nodeBase(node);\n const overlay = {\n root: void 0,\n pieces: void 0,\n baseOverrides: void 0,\n insertOverrides: void 0,\n structural: false,\n generation: 0,\n plan: void 0,\n seed: 2654435769,\n locatedOffset: 0,\n baseLocations: void 0,\n insertLocations: void 0\n };\n if (base.length > 0)\n overlay.root = createPieceNode(overlay, { kind: \"base\", start: 0, length: base.length, step: 1 });\n node.array = overlay;\n return overlay;\n }\n function baseOverridesForWrite(overlay) {\n if (overlay.baseOverrides === void 0)\n overlay.baseOverrides = /* @__PURE__ */ new Map();\n return overlay.baseOverrides;\n }\n function insertOverridesForWrite(overlay) {\n if (overlay.insertOverrides === void 0)\n overlay.insertOverrides = /* @__PURE__ */ new Map();\n return overlay.insertOverrides;\n }\n function nextPiecePriority(overlay) {\n let value = overlay.seed;\n value ^= value << 13;\n value ^= value >>> 17;\n value ^= value << 5;\n overlay.seed = value >>> 0;\n return overlay.seed;\n }\n function treeElements(node) {\n return node?.elements ?? 0;\n }\n function updatePieceNode(node) {\n node.elements = treeElements(node.left) + node.piece.length + treeElements(node.right);\n }\n function createPieceNode(overlay, piece) {\n return { piece, left: void 0, right: void 0, priority: nextPiecePriority(overlay), elements: piece.length };\n }\n function mergePieceTrees(left, right) {\n if (left === void 0)\n return right;\n if (right === void 0)\n return left;\n if (left.priority >= right.priority) {\n left.right = mergePieceTrees(left.right, right);\n updatePieceNode(left);\n return left;\n }\n right.left = mergePieceTrees(left, right.left);\n updatePieceNode(right);\n return right;\n }\n function splitPieceTree(overlay, root2, index3) {\n if (root2 === void 0)\n return [void 0, void 0];\n const leftLength = treeElements(root2.left);\n if (index3 < leftLength) {\n const [left, right] = splitPieceTree(overlay, root2.left, index3);\n root2.left = right;\n updatePieceNode(root2);\n return [left, root2];\n }\n const pieceEnd = leftLength + root2.piece.length;\n if (index3 > pieceEnd) {\n const [left, right] = splitPieceTree(overlay, root2.right, index3 - pieceEnd);\n root2.right = left;\n updatePieceNode(root2);\n return [root2, right];\n }\n if (index3 === leftLength) {\n const left = root2.left;\n root2.left = void 0;\n updatePieceNode(root2);\n return [left, root2];\n }\n if (index3 === pieceEnd) {\n const right = root2.right;\n root2.right = void 0;\n updatePieceNode(root2);\n return [root2, right];\n }\n const offset = index3 - leftLength;\n const first = { ...root2.piece, length: offset };\n const second = {\n ...root2.piece,\n start: root2.piece.start + root2.piece.step * offset,\n length: root2.piece.length - offset\n };\n return [\n mergePieceTrees(root2.left, createPieceNode(overlay, first)),\n mergePieceTrees(createPieceNode(overlay, second), root2.right)\n ];\n }\n function leftmostPieceNode(node) {\n while (node.left !== void 0)\n node = node.left;\n return node;\n }\n function rightmostPieceNode(node) {\n while (node.right !== void 0)\n node = node.right;\n return node;\n }\n function mergeablePieces(left, right) {\n if (left.kind !== right.kind)\n return false;\n if (left.kind === \"insert\" && left.source !== right.source)\n return false;\n if (left.length === 1 && right.length === 1)\n return Math.abs(right.start - left.start) === 1;\n return left.step === right.step && left.start + left.step * left.length === right.start;\n }\n function joinNormalized(overlay, left, right) {\n if (left === void 0)\n return right;\n if (right === void 0)\n return left;\n const leftPiece = rightmostPieceNode(left).piece;\n const rightPiece = leftmostPieceNode(right).piece;\n if (!mergeablePieces(leftPiece, rightPiece))\n return mergePieceTrees(left, right);\n const [leftRest] = splitPieceTree(overlay, left, treeElements(left) - leftPiece.length);\n const [, rightRest] = splitPieceTree(overlay, right, rightPiece.length);\n const step = leftPiece.length === 1 ? rightPiece.start - leftPiece.start : leftPiece.step;\n const combined = leftPiece.kind === \"base\" ? { kind: \"base\", start: leftPiece.start, length: leftPiece.length + rightPiece.length, step } : {\n kind: \"insert\",\n source: leftPiece.source,\n start: leftPiece.start,\n length: leftPiece.length + rightPiece.length,\n step\n };\n return joinNormalized(overlay, joinNormalized(overlay, leftRest, createPieceNode(overlay, combined)), rightRest);\n }\n function flattenPieceTree(node, output) {\n if (node === void 0)\n return;\n flattenPieceTree(node.left, output);\n output.push(node.piece);\n flattenPieceTree(node.right, output);\n }\n function piecesOf(overlay) {\n if (overlay.pieces === void 0) {\n overlay.pieces = [];\n flattenPieceTree(overlay.root, overlay.pieces);\n }\n return overlay.pieces;\n }\n function treeFromPieces(overlay, pieces) {\n mergePieces(pieces);\n let root2;\n for (const piece of pieces)\n root2 = mergePieceTrees(root2, createPieceNode(overlay, piece));\n return root2;\n }\n function replaceAllPieces(overlay, pieces) {\n overlay.root = treeFromPieces(overlay, pieces);\n overlay.pieces = void 0;\n overlay.baseLocations = void 0;\n overlay.insertLocations = void 0;\n }\n function arrayLength(overlay) {\n return treeElements(overlay.root);\n }\n function locatePiece(overlay, index3) {\n let node = overlay.root;\n while (node !== void 0) {\n const leftLength = treeElements(node.left);\n if (index3 < leftLength)\n node = node.left;\n else if (index3 >= leftLength + node.piece.length) {\n index3 -= leftLength + node.piece.length;\n node = node.right;\n } else {\n overlay.locatedOffset = index3 - leftLength;\n return node.piece;\n }\n }\n throw new RangeError(\"Array overlay index is out of range\");\n }\n function arrayIndex(property) {\n if (typeof property !== \"string\" || property.length === 0 || property.length > 10)\n return void 0;\n if (property === \"0\")\n return 0;\n const first = property.charCodeAt(0);\n if (first < 49 || first > 57)\n return void 0;\n let index3 = first - 48;\n for (let offset = 1; offset < property.length; offset++) {\n const digit = property.charCodeAt(offset) - 48;\n if (digit < 0 || digit > 9)\n return void 0;\n index3 = index3 * 10 + digit;\n if (index3 >= 4294967295)\n return void 0;\n }\n return index3;\n }\n function entryValueAt(node, piece, sourceIndex) {\n const overlay = arrayOverlay(node);\n if (piece.kind === \"base\") {\n const valueIndex = overlay.baseOverrides?.get(sourceIndex);\n return valueIndex === void 0 ? nodeBase(node)[sourceIndex] : storedValue(node.context, valueIndex);\n }\n const overrides = overlay.insertOverrides?.get(piece.source);\n const reference = overrides?.has(sourceIndex) ? overrides.get(sourceIndex) : piece.source.refs[sourceIndex];\n return storedValue(node.context, reference);\n }\n function hasEntryOverrideAt(overlay, piece, sourceIndex) {\n return piece.kind === \"base\" ? overlay.baseOverrides?.has(sourceIndex) ?? false : overlay.insertOverrides?.get(piece.source)?.has(sourceIndex) ?? false;\n }\n function extendRightmostPiece(node, amount) {\n if (node.right !== void 0)\n extendRightmostPiece(node.right, amount);\n else\n node.piece.length += amount;\n updatePieceNode(node);\n }\n function invalidatePieceCaches(overlay) {\n overlay.pieces = void 0;\n overlay.baseLocations = void 0;\n overlay.insertLocations = void 0;\n overlay.plan = void 0;\n }\n function replacePieceRange(node, index3, remove, inserted) {\n if (remove === 0 && inserted.length === 0)\n return;\n const overlay = arrayOverlay(node);\n if (remove === 0 && index3 === arrayLength(overlay) && inserted.length === 1 && overlay.root !== void 0) {\n const addition = inserted[0];\n const tail = rightmostPieceNode(overlay.root).piece;\n if (addition.kind === \"insert\" && tail.kind === \"insert\" && tail.step === 1 && tail.start + tail.length === tail.source.refs.length) {\n for (let offset = 0; offset < addition.length; offset++) {\n tail.source.refs.push(addition.source.refs[addition.start + offset]);\n }\n extendRightmostPiece(overlay.root, addition.length);\n invalidatePieceCaches(overlay);\n overlay.structural = true;\n overlay.generation += 1;\n markDirty(node);\n return;\n }\n }\n const [left, rest] = splitPieceTree(overlay, overlay.root, index3);\n const [, right] = splitPieceTree(overlay, rest, remove);\n const middle = treeFromPieces(overlay, inserted);\n overlay.root = joinNormalized(overlay, joinNormalized(overlay, left, middle), right);\n invalidatePieceCaches(overlay);\n overlay.structural = true;\n overlay.generation += 1;\n markDirty(node);\n }\n function mergePieces(pieces) {\n for (let index3 = 1; index3 < pieces.length; ) {\n const left = pieces[index3 - 1];\n const right = pieces[index3];\n const sameSource = left.kind === right.kind && (left.kind === \"base\" || left.source === right.source);\n if (sameSource && left.length === 1 && right.length === 1 && Math.abs(right.start - left.start) === 1) {\n left.step = right.start - left.start;\n left.length = 2;\n pieces.splice(index3, 1);\n } else if (sameSource && left.step === right.step && left.start + left.step * left.length === right.start) {\n left.length += right.length;\n pieces.splice(index3, 1);\n } else\n index3 += 1;\n }\n }\n function insertPiece(node, items, start = 0) {\n if (items.length === start)\n return [];\n const refs = [];\n for (let index3 = start; index3 < items.length; index3++)\n refs.push(storeValue(node.context, items[index3]));\n return [{ kind: \"insert\", source: { refs }, start: 0, length: refs.length, step: 1 }];\n }\n function insertPlacementPiece(node, values, start = 0) {\n if (values.length === start)\n return [];\n const storedLength = node.context.stored.length;\n try {\n for (let index3 = start; index3 < values.length; index3++)\n values[index3] = storeValue(node.context, clonePlacement(values[index3]));\n } catch (error) {\n node.context.stored.length = storedLength;\n throw error;\n }\n return [\n {\n kind: \"insert\",\n source: { refs: values },\n start,\n length: values.length - start,\n step: 1\n }\n ];\n }\n function setArrayIndex(node, index3, stored) {\n const overlay = arrayOverlay(node);\n const length = arrayLength(overlay);\n if (index3 === length) {\n replacePieceRange(node, length, 0, insertPiece(node, [stored]));\n return;\n }\n const piece = locatePiece(overlay, index3);\n const sourceIndex = piece.start + piece.step * overlay.locatedOffset;\n const current = entryValueAt(node, piece, sourceIndex);\n if (!isContainer2(stored) && current === stored)\n return;\n if (piece.kind === \"base\") {\n const existingIndex = overlay.baseOverrides?.get(sourceIndex);\n if (!isContainer2(stored) && stored === nodeBase(node)[sourceIndex]) {\n if (existingIndex !== void 0)\n releaseStoredValue(node.context, existingIndex);\n overlay.baseOverrides?.delete(sourceIndex);\n } else if (existingIndex === void 0) {\n baseOverridesForWrite(overlay).set(sourceIndex, storeValue(node.context, stored));\n } else\n overlay.baseOverrides.set(sourceIndex, replaceStoredValue(node.context, existingIndex, stored));\n } else {\n let overrides = overlay.insertOverrides?.get(piece.source);\n const existingIndex = overrides?.get(sourceIndex);\n if (!isContainer2(stored) && stored === storedValue(node.context, piece.source.refs[sourceIndex])) {\n if (existingIndex !== void 0)\n releaseStoredValue(node.context, existingIndex);\n overrides?.delete(sourceIndex);\n if (overrides?.size === 0)\n overlay.insertOverrides?.delete(piece.source);\n } else {\n if (overrides === void 0) {\n overrides = /* @__PURE__ */ new Map();\n insertOverridesForWrite(overlay).set(piece.source, overrides);\n }\n if (existingIndex === void 0)\n overrides.set(sourceIndex, storeValue(node.context, stored));\n else\n overrides.set(sourceIndex, replaceStoredValue(node.context, existingIndex, stored));\n }\n }\n markDirty(node);\n }\n function setArrayLength(node, next) {\n const current = arrayLength(arrayOverlay(node));\n if (next === current)\n return;\n if (next < current)\n replacePieceRange(node, next, current - next, []);\n else\n replacePieceRange(node, current, 0, insertPiece(node, Array.from({ length: next - current }, () => null)));\n }\n function toArrayLength(value) {\n const number = Number(value);\n if (!Number.isInteger(number) || number < 0 || number >= 4294967296)\n throw new RangeError(\"Invalid array length\");\n return number;\n }\n function toIntegerOrInfinity(value) {\n const number = Number(value);\n if (Number.isNaN(number) || number === 0)\n return 0;\n return Number.isFinite(number) ? Math.trunc(number) : number;\n }\n function clampIndex(value, length) {\n if (value === Number.NEGATIVE_INFINITY)\n return 0;\n if (value < 0)\n return Math.max(length + value, 0);\n return Math.min(value, length);\n }\n function mutatorNode(receiver) {\n if (!isContainer2(receiver))\n return void 0;\n const node = Reflect.get(receiver, NODE);\n if (node === void 0)\n return void 0;\n if (!Array.isArray(nodeBase(node)))\n throw new TypeError(\"Array mutator called on incompatible receiver\");\n assertWritable(node.context);\n return node;\n }\n var arrayMutators = {\n push(...items) {\n const node = mutatorNode(this);\n if (node === void 0)\n return Reflect.apply(Array.prototype.push, this, items);\n const length = arrayLength(arrayOverlay(node));\n replacePieceRange(node, length, 0, insertPlacementPiece(node, items));\n return length + items.length;\n },\n pop() {\n const node = mutatorNode(this);\n if (node === void 0)\n return Reflect.apply(Array.prototype.pop, this, []);\n const length = arrayLength(arrayOverlay(node));\n if (length === 0)\n return void 0;\n const value = getArrayIndex(node, length - 1);\n replacePieceRange(node, length - 1, 1, []);\n return value;\n },\n shift() {\n const node = mutatorNode(this);\n if (node === void 0)\n return Reflect.apply(Array.prototype.shift, this, []);\n const length = arrayLength(arrayOverlay(node));\n if (length === 0)\n return void 0;\n const value = getArrayIndex(node, 0);\n replacePieceRange(node, 0, 1, []);\n return value;\n },\n unshift(...items) {\n const node = mutatorNode(this);\n if (node === void 0)\n return Reflect.apply(Array.prototype.unshift, this, items);\n replacePieceRange(node, 0, 0, insertPlacementPiece(node, items));\n return arrayLength(arrayOverlay(node));\n },\n splice(...args) {\n const node = mutatorNode(this);\n if (node === void 0)\n return Reflect.apply(Array.prototype.splice, this, args);\n const length = arrayLength(arrayOverlay(node));\n const start = args.length === 0 ? 0 : clampIndex(toIntegerOrInfinity(args[0]), length);\n const remove = args.length === 0 ? 0 : args.length === 1 ? length - start : Math.min(Math.max(toIntegerOrInfinity(args[1]), 0), length - start);\n const removed = Array.from({ length: remove }, (_, offset) => getArrayIndex(node, start + offset));\n const itemStart = Math.min(2, args.length);\n const itemCount = Math.max(args.length - 2, 0);\n replacePieceRange(node, start, remove, insertPlacementPiece(node, args, itemStart));\n setArrayLength(node, length - remove + itemCount);\n return removed;\n },\n reverse() {\n const node = mutatorNode(this);\n if (node === void 0)\n return Reflect.apply(Array.prototype.reverse, this, []);\n const overlay = arrayOverlay(node);\n if (arrayLength(overlay) < 2)\n return node.proxy;\n const pieces = [...piecesOf(overlay)].reverse();\n for (const piece of pieces) {\n piece.start += piece.step * (piece.length - 1);\n piece.step = piece.step === 1 ? -1 : 1;\n }\n replaceAllPieces(overlay, pieces);\n overlay.structural = true;\n overlay.generation += 1;\n overlay.plan = void 0;\n markDirty(node);\n return node.proxy;\n },\n sort(comparator) {\n const node = mutatorNode(this);\n if (node === void 0)\n return Reflect.apply(Array.prototype.sort, this, [comparator]);\n if (comparator !== void 0 && typeof comparator !== \"function\")\n throw new TypeError(\"Comparator must be a function\");\n const overlay = arrayOverlay(node);\n const insertedSources = [];\n const insertedIndices = [];\n const insertedValues = [];\n const baseValues = new Array(nodeBase(node).length);\n const order = [];\n for (const piece of piecesOf(overlay)) {\n for (let offset = 0; offset < piece.length; offset++) {\n const sourceIndex = piece.start + piece.step * offset;\n if (piece.kind === \"base\") {\n order.push(sourceIndex);\n baseValues[sourceIndex] = publicSortValue(node, sourceIndex, insertedSources, insertedIndices);\n } else {\n insertedSources.push(piece.source);\n insertedIndices.push(sourceIndex);\n const token = -insertedSources.length;\n order.push(token);\n insertedValues.push(publicSortValue(node, token, insertedSources, insertedIndices));\n }\n }\n }\n const baseSnapshot = /* @__PURE__ */ new Map();\n for (const [index3, valueIndex] of overlay.baseOverrides ?? [])\n baseSnapshot.set(index3, storedValue(node.context, valueIndex));\n const insertSnapshots = /* @__PURE__ */ new Map();\n for (const [source, overrides] of overlay.insertOverrides ?? []) {\n const snapshot = /* @__PURE__ */ new Map();\n for (const [index3, valueIndex] of overrides)\n snapshot.set(index3, storedValue(node.context, valueIndex));\n insertSnapshots.set(source, snapshot);\n }\n const generation = overlay.generation;\n order.sort((left, right) => {\n const leftValue = left < 0 ? insertedValues[-left - 1] : baseValues[left];\n const rightValue = right < 0 ? insertedValues[-right - 1] : baseValues[right];\n if (typeof comparator === \"function\")\n return Number(comparator(leftValue, rightValue));\n const a = String(leftValue);\n const b = String(rightValue);\n return a < b ? -1 : a > b ? 1 : 0;\n });\n if (baseSnapshot.size > 0 || insertSnapshots.size > 0 || (overlay.baseOverrides?.size ?? 0) > 0 || (overlay.insertOverrides?.size ?? 0) > 0) {\n for (const token of order) {\n restoreSortOverride(node, token, insertedSources, insertedIndices, baseSnapshot, insertSnapshots);\n }\n }\n const comparatorWasStructural = overlay.generation !== generation;\n const currentLength = arrayLength(overlay);\n const samePrefix = currentLength >= order.length && order.every((token, index3) => sameSortTokenAt(overlay, index3, token, insertedSources, insertedIndices));\n if (!samePrefix) {\n replacePieceRange(node, 0, Math.min(order.length, currentLength), piecesFromSortOrder(order, insertedSources, insertedIndices));\n }\n if (comparatorWasStructural)\n deduplicateArrayEntries(node);\n return node.proxy;\n },\n fill(supplied, startArg, endArg) {\n const node = mutatorNode(this);\n if (node === void 0)\n return Reflect.apply(Array.prototype.fill, this, [supplied, startArg, endArg]);\n const length = arrayLength(arrayOverlay(node));\n const start = startArg === void 0 ? 0 : clampIndex(toIntegerOrInfinity(startArg), length);\n const end = endArg === void 0 ? length : clampIndex(toIntegerOrInfinity(endArg), length);\n if (end <= start)\n return node.proxy;\n const items = Array.from({ length: end - start }, () => clonePlacement(supplied));\n replacePieceRange(node, start, end - start, insertPiece(node, items));\n return node.proxy;\n },\n copyWithin(targetArg, startArg, endArg) {\n const node = mutatorNode(this);\n if (node === void 0)\n return Reflect.apply(Array.prototype.copyWithin, this, [targetArg, startArg, endArg]);\n const length = arrayLength(arrayOverlay(node));\n const target = clampIndex(toIntegerOrInfinity(targetArg), length);\n const start = clampIndex(toIntegerOrInfinity(startArg), length);\n const end = endArg === void 0 ? length : clampIndex(toIntegerOrInfinity(endArg), length);\n const count = Math.min(Math.max(end - start, 0), length - target);\n const values = Array.from({ length: count }, (_, offset) => clonePlacement(getArrayIndex(node, start + offset)));\n replacePieceRange(node, target, count, insertPiece(node, values));\n return node.proxy;\n }\n };\n function sortTokenSource(token, sources2) {\n return token < 0 ? sources2[-token - 1] : void 0;\n }\n function sortTokenIndex(token, indices) {\n return token < 0 ? indices[-token - 1] : token;\n }\n function publicSortValue(node, token, sources2, indices) {\n const overlay = arrayOverlay(node);\n const source = sortTokenSource(token, sources2);\n const sourceIndex = sortTokenIndex(token, indices);\n const overrideIndex = source === void 0 ? overlay.baseOverrides?.get(sourceIndex) : overlay.insertOverrides?.get(source)?.get(sourceIndex);\n const value = overrideIndex !== void 0 ? storedValue(node.context, overrideIndex) : source === void 0 ? nodeBase(node)[sourceIndex] : storedValue(node.context, source.refs[sourceIndex]);\n if (!isContainer2(value))\n return value;\n return createNode(node.context, value, node, source === void 0 ? 1 : 2, sourceIndex, source, source !== void 0 || (overlay.baseOverrides?.has(sourceIndex) ?? false)).proxy;\n }\n function restoreSortOverride(node, token, sources2, indices, baseSnapshot, insertSnapshots) {\n const overlay = arrayOverlay(node);\n const source = sortTokenSource(token, sources2);\n const sourceIndex = sortTokenIndex(token, indices);\n if (source === void 0) {\n const existingIndex2 = overlay.baseOverrides?.get(sourceIndex);\n const snapshotValue2 = baseSnapshot.get(sourceIndex);\n if (snapshotValue2 !== void 0) {\n if (existingIndex2 === void 0)\n baseOverridesForWrite(overlay).set(sourceIndex, storeValue(node.context, snapshotValue2));\n else\n overlay.baseOverrides.set(sourceIndex, replaceStoredValue(node.context, existingIndex2, snapshotValue2));\n } else {\n if (existingIndex2 !== void 0)\n releaseStoredValue(node.context, existingIndex2);\n overlay.baseOverrides?.delete(sourceIndex);\n }\n return;\n }\n let overrides = overlay.insertOverrides?.get(source);\n const existingIndex = overrides?.get(sourceIndex);\n const snapshotValue = insertSnapshots.get(source)?.get(sourceIndex);\n if (snapshotValue !== void 0) {\n if (overrides === void 0) {\n overrides = /* @__PURE__ */ new Map();\n insertOverridesForWrite(overlay).set(source, overrides);\n }\n if (existingIndex === void 0)\n overrides.set(sourceIndex, storeValue(node.context, snapshotValue));\n else\n overrides.set(sourceIndex, replaceStoredValue(node.context, existingIndex, snapshotValue));\n } else {\n if (existingIndex !== void 0)\n releaseStoredValue(node.context, existingIndex);\n overrides?.delete(sourceIndex);\n if (overrides?.size === 0)\n overlay.insertOverrides?.delete(source);\n }\n }\n function sameSortTokenAt(overlay, logicalIndex, token, sources2, indices) {\n const piece = locatePiece(overlay, logicalIndex);\n const sourceIndex = piece.start + piece.step * overlay.locatedOffset;\n const tokenSource = sortTokenSource(token, sources2);\n return sourceIndex === sortTokenIndex(token, indices) && (piece.kind === \"base\" && tokenSource === void 0 || piece.kind === \"insert\" && piece.source === tokenSource);\n }\n function deduplicateArrayEntries(node) {\n const overlay = arrayOverlay(node);\n const seenBase = /* @__PURE__ */ new Set();\n const seenInsert = /* @__PURE__ */ new Map();\n const next = [];\n let duplicated = false;\n for (const piece of piecesOf(overlay)) {\n for (let offset = 0; offset < piece.length; offset++) {\n const sourceIndex = piece.start + piece.step * offset;\n let seen;\n if (piece.kind === \"base\") {\n seen = seenBase.has(sourceIndex);\n seenBase.add(sourceIndex);\n } else {\n let indices = seenInsert.get(piece.source);\n if (indices === void 0) {\n indices = /* @__PURE__ */ new Set();\n seenInsert.set(piece.source, indices);\n }\n seen = indices.has(sourceIndex);\n indices.add(sourceIndex);\n }\n if (seen) {\n duplicated = true;\n appendMergedPiece(next, insertPiece(node, [clonePlacementStored(entryValueAt(node, piece, sourceIndex), node.context)])[0]);\n } else\n appendMergedPiece(next, singletonPiece(piece, sourceIndex));\n }\n }\n if (!duplicated)\n return;\n replaceAllPieces(overlay, next);\n overlay.structural = true;\n overlay.generation += 1;\n overlay.plan = void 0;\n markDirty(node);\n }\n function piecesFromSortOrder(order, sources2, indices) {\n const pieces = [];\n for (const token of order) {\n const source = token < 0 ? sources2[-token - 1] : void 0;\n const sourceIndex = token < 0 ? indices[-token - 1] : token;\n const previous = pieces.at(-1);\n const sameSource = previous !== void 0 && (source === void 0 && previous.kind === \"base\" || source !== void 0 && previous.kind === \"insert\" && previous.source === source);\n if (previous !== void 0 && sameSource) {\n if (previous.length === 1) {\n const step = sourceIndex - previous.start;\n if (step === 1 || step === -1) {\n previous.step = step;\n previous.length = 2;\n continue;\n }\n } else if (previous.start + previous.step * previous.length === sourceIndex) {\n previous.length += 1;\n continue;\n }\n }\n pieces.push(source === void 0 ? { kind: \"base\", start: sourceIndex, length: 1, step: 1 } : { kind: \"insert\", source, start: sourceIndex, length: 1, step: 1 });\n }\n return pieces;\n }\n function appendMergedPiece(pieces, piece) {\n const previous = pieces.at(-1);\n const sameSource = previous !== void 0 && previous.kind === piece.kind && (previous.kind === \"base\" || previous.source === piece.source);\n if (previous !== void 0 && sameSource && previous.length === 1 && piece.length === 1) {\n const step = piece.start - previous.start;\n if (step === 1 || step === -1) {\n previous.step = step;\n previous.length = 2;\n return;\n }\n }\n if (previous !== void 0 && sameSource && previous.step === piece.step && previous.start + previous.step * previous.length === piece.start) {\n previous.length += piece.length;\n } else\n pieces.push(piece);\n }\n function singletonPiece(piece, sourceIndex) {\n return piece.kind === \"base\" ? { kind: \"base\", start: sourceIndex, length: 1, step: 1 } : { kind: \"insert\", source: piece.source, start: sourceIndex, length: 1, step: 1 };\n }\n function clonePlacement(value) {\n const proxyNode = isContainer2(value) ? Reflect.get(value, NODE) : void 0;\n return proxyNode === void 0 ? copyJson(value) : clonePlacementNode(proxyNode);\n }\n function cloneNode(node) {\n assertReadable(node.context);\n if (Array.isArray(nodeBase(node))) {\n const overlay = arrayOverlay(node);\n const result2 = [];\n for (const piece of piecesOf(overlay)) {\n for (let offset = 0; offset < piece.length; offset++) {\n const sourceIndex = piece.start + piece.step * offset;\n result2.push(cloneStored(entryValueAt(node, piece, sourceIndex), node.context));\n }\n }\n return result2;\n }\n const result = Object.create(Object.getPrototypeOf(nodeBase(node)));\n for (const key of ownKeys(node))\n defineData3(result, key, cloneStored(objectValue(node, key), node.context));\n return result;\n }\n function cloneStored(value, context2) {\n if (!isContainer2(value))\n return value;\n const node = context2.rawNodes.get(value);\n return node === void 0 || !node.dirty && !node.subtreeDirty ? value : cloneNode(node);\n }\n function clonePlacementNode(node) {\n assertReadable(node.context);\n if (Array.isArray(nodeBase(node))) {\n const overlay = arrayOverlay(node);\n const result2 = [];\n for (const piece of piecesOf(overlay)) {\n for (let offset = 0; offset < piece.length; offset++) {\n const sourceIndex = piece.start + piece.step * offset;\n result2.push(clonePlacementStored(entryValueAt(node, piece, sourceIndex), node.context));\n }\n }\n return result2;\n }\n const result = Object.create(Object.getPrototypeOf(nodeBase(node)));\n for (const key of ownKeys(node))\n defineData3(result, key, clonePlacementStored(objectValue(node, key), node.context));\n return result;\n }\n function clonePlacementStored(value, context2) {\n if (!isContainer2(value))\n return copyJson(value);\n const node = context2.rawNodes.get(value);\n return node === void 0 ? copyJson(value) : clonePlacementNode(node);\n }\n function defineData3(target, key, value) {\n DATA_DESCRIPTOR3.value = value;\n Object.defineProperty(target, key, DATA_DESCRIPTOR3);\n DATA_DESCRIPTOR3.value = void 0;\n }\n function emitOperations(context2) {\n const simple = emitSimpleObjectOperations(context2);\n if (simple !== void 0)\n return simple;\n const operations = [];\n const forcedFolds = /* @__PURE__ */ new Map();\n const emissionPaths = /* @__PURE__ */ new Map();\n const denseIndices = /* @__PURE__ */ new Map();\n for (const node of context2.dirty) {\n recordDenseArrayPosition(node, denseIndices);\n if (Array.isArray(nodeBase(node))) {\n const overlay = arrayOverlay(node);\n if (!overlay.structural && (overlay.baseOverrides?.size ?? 0) > 0) {\n let candidates = denseIndices.get(node);\n if (candidates === void 0) {\n candidates = { indices: [], bits: void 0, length: nodeBase(node).length };\n denseIndices.set(node, candidates);\n }\n for (const index3 of overlay.baseOverrides.keys())\n addDenseCandidate(candidates, index3);\n }\n }\n }\n const denseRegions = /* @__PURE__ */ new Map();\n for (const [array, candidates] of denseIndices) {\n const path = resolvePath(array);\n if (path === void 0 || path.some((segment) => typeof segment === \"string\" && RESERVED_SEGMENTS.has(segment))) {\n continue;\n }\n const regions = buildDenseRegions(candidates);\n if (regions.length > 0)\n denseRegions.set(array, regions);\n }\n for (const node of context2.dirty) {\n const path = resolvePath(node);\n if (path === void 0)\n continue;\n if (hasCoveringDenseRegion(node, path, denseRegions))\n continue;\n emissionPaths.set(node, path);\n if (!Array.isArray(nodeBase(node)) && hasReservedMutation(node))\n forcedFolds.set(node, path);\n const reservedAt = path.findIndex((segment) => typeof segment === \"string\" && RESERVED_SEGMENTS.has(segment));\n if (reservedAt >= 0) {\n let ancestor = node;\n for (let depth = path.length; depth > reservedAt; depth--)\n ancestor = nodeParent(ancestor);\n forcedFolds.set(ancestor, path.slice(0, reservedAt));\n }\n }\n for (const [node, path] of forcedFolds)\n emissionPaths.set(node, path);\n for (const node of denseRegions.keys()) {\n const path = resolvePath(node);\n if (path !== void 0 && !hasCoveringDenseRegion(node, path, denseRegions))\n emissionPaths.set(node, path);\n }\n let maxDepth = 0;\n for (const path of emissionPaths.values())\n maxDepth = Math.max(maxDepth, path.length);\n const buckets = Array.from({ length: maxDepth + 1 }, () => []);\n for (const [node, path] of emissionPaths)\n buckets[path.length].push(node);\n const folded = /* @__PURE__ */ new Set();\n for (const bucket of buckets) {\n for (const node of bucket) {\n const path = emissionPaths.get(node);\n if (hasPlacementAncestor(node) || hasFoldedAncestor(node, folded))\n continue;\n if (forcedFolds.has(node)) {\n emitSet(operations, path, cloneNode(node));\n folded.add(node);\n continue;\n }\n if (Array.isArray(nodeBase(node)))\n emitArrayOperations(node, path, operations, denseRegions.get(node));\n else\n emitObjectOperations(node, path, operations);\n if (operations.length > MAX_DELTA_OPERATIONS) {\n locatedDenseArray = void 0;\n return [[\"r\", cloneNode(context2.root)]];\n }\n }\n }\n locatedDenseArray = void 0;\n return operations;\n }\n function emitSimpleObjectOperations(context2) {\n const nodes = [];\n for (const node of context2.dirty) {\n if (Array.isArray(nodeBase(node)) || hasReservedMutation(node) || hasPlacementAncestor(node))\n return void 0;\n for (let parent = nodeParent(node); parent !== void 0; parent = nodeParent(parent)) {\n if (Array.isArray(nodeBase(parent)))\n return void 0;\n }\n const path = resolvePath(node);\n if (path === void 0)\n continue;\n for (const segment of path) {\n if (typeof segment === \"string\" && RESERVED_SEGMENTS.has(segment))\n return void 0;\n }\n nodes.push(node);\n if (nodes.length > MAX_SIMPLE_OBJECT_NODES)\n return void 0;\n }\n for (let index3 = 1; index3 < nodes.length; index3++) {\n const node = nodes[index3];\n const depth = node.preparedPath.length;\n let at = index3;\n while (at > 0 && nodes[at - 1].preparedPath.length > depth) {\n nodes[at] = nodes[at - 1];\n at -= 1;\n }\n nodes[at] = node;\n }\n const operations = [];\n let canMaterializeDirectly = true;\n for (const node of nodes) {\n if (emitObjectOperations(node, node.preparedPath, operations))\n canMaterializeDirectly = false;\n if (operations.length > MAX_DELTA_OPERATIONS)\n return [[\"r\", cloneNode(context2.root)]];\n }\n context2.simpleObjectMaterialization = canMaterializeDirectly;\n return operations;\n }\n var locatedDenseArray;\n var locatedDenseIndex = 0;\n function locateDenseArrayPosition(node) {\n let child = node;\n for (let parent = nodeParent(child); parent !== void 0; parent = nodeParent(child)) {\n if (Array.isArray(nodeBase(parent))) {\n const overlay = arrayOverlay(parent);\n if (child.parentKind !== 1 || overlay.structural)\n return false;\n const sourceIndex = child.parentKey;\n const valueIndex = overlay.baseOverrides?.get(sourceIndex);\n const current = valueIndex === void 0 ? nodeBase(parent)[sourceIndex] : storedValue(parent.context, valueIndex);\n if (current !== nodeBase(child))\n return false;\n locatedDenseArray = parent;\n locatedDenseIndex = sourceIndex;\n return true;\n }\n child = parent;\n }\n return false;\n }\n function hasCoveringDenseRegion(node, path, denseRegions) {\n for (let parent = nodeParent(node); parent !== void 0; parent = nodeParent(parent)) {\n const regions = denseRegions.get(parent);\n if (regions === void 0)\n continue;\n const parentPath = resolvePath(parent);\n if (parentPath === void 0 || path.length <= parentPath.length)\n continue;\n let matches = true;\n for (let index4 = 0; index4 < parentPath.length; index4++) {\n if (path[index4] !== parentPath[index4]) {\n matches = false;\n break;\n }\n }\n if (!matches)\n continue;\n const index3 = path[parentPath.length];\n if (typeof index3 === \"number\" && regionContaining(regions, index3))\n return true;\n }\n return false;\n }\n function addDenseCandidate(candidates, index3) {\n if (candidates.bits !== void 0) {\n candidates.bits[index3] = 1;\n return;\n }\n candidates.indices.push(index3);\n if (candidates.indices.length < 256)\n return;\n candidates.bits = new Uint8Array(candidates.length);\n for (const existing of candidates.indices)\n candidates.bits[existing] = 1;\n candidates.indices.length = 0;\n }\n function recordDenseArrayPosition(node, groups) {\n if (!locateDenseArrayPosition(node))\n return;\n let candidates = groups.get(locatedDenseArray);\n if (candidates === void 0) {\n candidates = { indices: [], bits: void 0, length: nodeBase(locatedDenseArray).length };\n groups.set(locatedDenseArray, candidates);\n }\n addDenseCandidate(candidates, locatedDenseIndex);\n }\n function buildDenseRegions(candidates) {\n if (candidates.bits === void 0)\n return [];\n const regions = [];\n const bits = candidates.bits;\n for (let at = 0; at < bits.length; ) {\n while (at < bits.length && bits[at] === 0)\n at += 1;\n if (at === bits.length)\n break;\n const start = at;\n let end = at;\n let count = 0;\n let gap = 0;\n while (at < bits.length) {\n if (bits[at] !== 0) {\n count += 1;\n end = at;\n gap = 0;\n } else if (++gap > 1)\n break;\n at += 1;\n }\n const length = end - start + 1;\n if (count >= 256 && count * 2 >= length)\n regions.push({ start, length });\n }\n return regions;\n }\n function regionContaining(regions, index3) {\n for (const region of regions)\n if (index3 >= region.start && index3 < region.start + region.length)\n return true;\n return false;\n }\n function hasReservedMutation(node) {\n if (node.writeKey !== void 0 && RESERVED_SEGMENTS.has(node.writeKey))\n return true;\n if (node.deleteKey !== void 0 && RESERVED_SEGMENTS.has(node.deleteKey))\n return true;\n if (node.writes !== void 0) {\n for (const key of node.writes.keys())\n if (RESERVED_SEGMENTS.has(key))\n return true;\n }\n if (node.deletes !== void 0) {\n for (const key of node.deletes)\n if (RESERVED_SEGMENTS.has(key))\n return true;\n }\n return false;\n }\n function hasFoldedAncestor(node, folded) {\n for (let parent = nodeParent(node); parent !== void 0; parent = nodeParent(parent))\n if (folded.has(parent))\n return true;\n return false;\n }\n function hasPlacementAncestor(node) {\n for (let current = node; current !== void 0; current = nodeParent(current)) {\n if (nodeParent(current) !== void 0 && current.parentPlacement)\n return true;\n }\n return false;\n }\n function emitObjectWrite(node, path, operations, key, value) {\n const nextPath = [...path, key];\n const before = node.readded?.has(key) || !Object.hasOwn(nodeBase(node), key) ? void 0 : nodeBase(node)[key];\n const after = cloneStored(value, node.context);\n const emitted = emitChangedValue(operations, nextPath, before, after);\n return isContainer2(before) && isContainer2(after) && !emitted;\n }\n function emitObjectOperations(node, path, operations) {\n if (node.readded !== void 0) {\n for (const key of node.readded) {\n if (Object.hasOwn(nodeBase(node), key))\n operations.push([\"d\", [...path, key]]);\n }\n }\n let normalizedContainerWrite = false;\n if (node.writeKey !== void 0)\n normalizedContainerWrite = emitObjectWrite(node, path, operations, node.writeKey, objectValue(node, node.writeKey));\n if (node.writes !== void 0) {\n for (const [key, valueIndex] of node.writes) {\n if (operations.length > MAX_DELTA_OPERATIONS)\n return normalizedContainerWrite;\n if (emitObjectWrite(node, path, operations, key, storedValue(node.context, valueIndex)))\n normalizedContainerWrite = true;\n }\n }\n if (node.deleteKey !== void 0 && Object.hasOwn(nodeBase(node), node.deleteKey)) {\n operations.push([\"d\", [...path, node.deleteKey]]);\n }\n if (node.deletes !== void 0) {\n for (const key of node.deletes) {\n if (operations.length > MAX_DELTA_OPERATIONS)\n return normalizedContainerWrite;\n if (Object.hasOwn(nodeBase(node), key))\n operations.push([\"d\", [...path, key]]);\n }\n }\n return normalizedContainerWrite;\n }\n function buildArrayPlan(node) {\n const overlay = arrayOverlay(node);\n if (overlay.plan !== void 0)\n return overlay.plan;\n const base = nodeBase(node);\n const pieces = piecesOf(overlay);\n const retained = new Uint8Array(base.length);\n const targetBase = [];\n for (const piece of pieces) {\n if (piece.kind !== \"base\")\n continue;\n for (let offset = 0; offset < piece.length; offset++) {\n const index3 = piece.start + piece.step * offset;\n retained[index3] = 1;\n targetBase.push(index3);\n }\n }\n const removeRuns = [];\n for (let end = base.length; end > 0; ) {\n if (retained[end - 1] !== 0) {\n end -= 1;\n continue;\n }\n let start = end - 1;\n while (start > 0 && retained[start - 1] === 0)\n start -= 1;\n removeRuns.push(start, end - start);\n end = start;\n }\n const retainedBase = [];\n for (let index3 = 0; index3 < retained.length; index3++)\n if (retained[index3] !== 0)\n retainedBase.push(index3);\n let permutation;\n if (targetBase.some((value, index3) => value !== retainedBase[index3])) {\n const positions = new Map(retainedBase.map((value, index3) => [value, index3]));\n permutation = targetBase.map((value) => positions.get(value));\n }\n const insertRuns = [];\n let logicalIndex = 0;\n for (let pieceIndex = 0; pieceIndex < pieces.length; ) {\n const piece = pieces[pieceIndex];\n if (piece.kind === \"base\") {\n logicalIndex += piece.length;\n pieceIndex += 1;\n continue;\n }\n const startPiece = pieceIndex;\n while (pieceIndex < pieces.length && pieces[pieceIndex].kind === \"insert\") {\n logicalIndex += pieces[pieceIndex].length;\n pieceIndex += 1;\n }\n insertRuns.push(logicalIndex - rangeLength(pieces, startPiece, pieceIndex), startPiece, pieceIndex);\n }\n overlay.plan = { removeRuns, permutation, insertRuns };\n return overlay.plan;\n }\n function rangeLength(pieces, start, end) {\n let length = 0;\n for (let index3 = start; index3 < end; index3++)\n length += pieces[index3].length;\n return length;\n }\n function emitArrayOperations(node, path, operations, denseRegions) {\n const overlay = arrayOverlay(node);\n const base = nodeBase(node);\n if (denseRegions !== void 0) {\n for (const region of denseRegions) {\n if (operations.length > MAX_DELTA_OPERATIONS)\n return;\n operations.push([\"p\", path, region.start, region.length, cloneArrayRegion(node, region)]);\n }\n }\n if (overlay.structural) {\n const plan = buildArrayPlan(node);\n for (let index3 = 0; index3 < plan.removeRuns.length; index3 += 2) {\n if (operations.length > MAX_DELTA_OPERATIONS)\n return;\n operations.push([\"p\", path, plan.removeRuns[index3], plan.removeRuns[index3 + 1], []]);\n }\n if (plan.permutation !== void 0)\n operations.push([\"m\", path, plan.permutation]);\n const pieces = piecesOf(overlay);\n for (let run2 = 0; run2 < plan.insertRuns.length; run2 += 3) {\n if (operations.length > MAX_DELTA_OPERATIONS)\n return;\n const logicalIndex = plan.insertRuns[run2];\n const items = [];\n for (let pieceIndex = plan.insertRuns[run2 + 1]; pieceIndex < plan.insertRuns[run2 + 2]; pieceIndex++) {\n const piece = pieces[pieceIndex];\n for (let offset = 0; offset < piece.length; offset++) {\n const sourceIndex = piece.start + piece.step * offset;\n items.push(cloneStored(entryValueAt(node, piece, sourceIndex), node.context));\n }\n }\n operations.push([\"p\", path, logicalIndex, 0, items]);\n }\n }\n for (const [baseIndex, valueIndex] of overlay.baseOverrides ?? []) {\n if (operations.length > MAX_DELTA_OPERATIONS)\n return;\n const index3 = findEntryIndex(overlay, 1, baseIndex, void 0);\n if (index3 === void 0 || denseRegions !== void 0 && regionContaining(denseRegions, index3))\n continue;\n emitChangedValue(operations, [...path, index3], base[baseIndex], cloneStored(storedValue(node.context, valueIndex), node.context));\n }\n }\n function cloneArrayRegion(node, region) {\n const overlay = arrayOverlay(node);\n const result = [];\n for (let index3 = region.start; index3 < region.start + region.length; index3++) {\n const piece = locatePiece(overlay, index3);\n const sourceIndex = piece.start + piece.step * overlay.locatedOffset;\n result.push(cloneStored(entryValueAt(node, piece, sourceIndex), node.context));\n }\n return result;\n }\n function emitChangedValue(operations, path, before, after) {\n if (!isContainer2(after) && before === after)\n return false;\n if (isContainer2(before) && isContainer2(after) && equalTrustedJson(before, after))\n return false;\n if (typeof before === \"string\" && typeof after === \"string\") {\n if (after.length > before.length && after.slice(0, before.length) === before) {\n operations.push([\"a\", path, after.slice(before.length)]);\n return true;\n }\n const shared = overlap(before, after, 65536);\n if (shared > 0) {\n operations.push([\"t\", path, before.length - shared]);\n if (after.length > shared)\n operations.push([\"a\", path, after.slice(shared)]);\n return true;\n }\n }\n operations.push([\"s\", path, after]);\n return true;\n }\n function emitSet(operations, path, value) {\n if (path.length === 0)\n operations.push([\"r\", value]);\n else\n operations.push([\"s\", path, value]);\n }\n function resolvePath(node) {\n if (node.preparedPath !== void 0)\n return node.preparedPath;\n const parent = nodeParent(node);\n if (parent === void 0) {\n node.preparedPath = [];\n return node.preparedPath;\n }\n const parentPath = resolvePath(parent);\n if (parentPath === void 0)\n return void 0;\n if (node.parentKind === 0) {\n const key = node.parentKey;\n if (!objectHas(parent, key) || objectValue(parent, key) !== nodeBase(node))\n return void 0;\n node.preparedPath = [...parentPath, key];\n return node.preparedPath;\n }\n const overlay = arrayOverlay(parent);\n const index3 = findEntryIndex(overlay, node.parentKind, node.parentKey, node.parentSource);\n if (index3 === void 0)\n return void 0;\n const piece = locatePiece(overlay, index3);\n if (entryValueAt(parent, piece, node.parentKey) !== nodeBase(node))\n return void 0;\n node.preparedPath = [...parentPath, index3];\n return node.preparedPath;\n }\n function ensurePieceLocations(overlay) {\n if (overlay.baseLocations !== void 0)\n return;\n overlay.baseLocations = [];\n overlay.insertLocations = /* @__PURE__ */ new Map();\n let logicalStart = 0;\n for (const piece of piecesOf(overlay)) {\n const last = piece.start + piece.step * (piece.length - 1);\n const location = {\n piece,\n logicalStart,\n minimum: Math.min(piece.start, last),\n maximum: Math.max(piece.start, last)\n };\n if (piece.kind === \"base\")\n overlay.baseLocations.push(location);\n else {\n let locations = overlay.insertLocations.get(piece.source);\n if (locations === void 0) {\n locations = [];\n overlay.insertLocations.set(piece.source, locations);\n }\n locations.push(location);\n }\n logicalStart += piece.length;\n }\n const byMinimum = (left, right) => left.minimum - right.minimum;\n overlay.baseLocations.sort(byMinimum);\n for (const locations of overlay.insertLocations.values())\n locations.sort(byMinimum);\n }\n function findEntryIndex(overlay, kind, sourceIndex, source) {\n if (kind === 1 && !overlay.structural)\n return sourceIndex;\n ensurePieceLocations(overlay);\n const locations = kind === 1 ? overlay.baseLocations : overlay.insertLocations.get(source);\n if (locations === void 0)\n return void 0;\n let low = 0;\n let high = locations.length;\n while (low < high) {\n const middle = low + high >>> 1;\n if (locations[middle].minimum <= sourceIndex)\n low = middle + 1;\n else\n high = middle;\n }\n const location = locations[low - 1];\n if (location === void 0 || sourceIndex > location.maximum)\n return void 0;\n const offset = (sourceIndex - location.piece.start) / location.piece.step;\n return offset >= 0 && offset < location.piece.length ? location.logicalStart + offset : void 0;\n }\n function ensureOperations(context2) {\n if (context2.ops !== void 0)\n return context2.ops;\n assertReadable(context2);\n if (context2.replacement) {\n const base = context2.tracker.deref()?.replacementBase(context2);\n context2.replacementNoop = base !== void 0 && equalTrustedJson(base, nodeBase(context2.root));\n context2.ops = context2.replacementNoop ? [] : [[\"r\", nodeBase(context2.root)]];\n } else\n context2.ops = emitOperations(context2);\n return context2.ops;\n }\n function equalTrustedJson(left, right) {\n if (left === right)\n return true;\n if (!isContainer2(left) || !isContainer2(right) || Array.isArray(left) !== Array.isArray(right))\n return false;\n if (Array.isArray(left)) {\n const other2 = right;\n if (left.length !== other2.length)\n return false;\n for (let index3 = 0; index3 < left.length; index3++)\n if (!equalTrustedJson(left[index3], other2[index3]))\n return false;\n return true;\n }\n const other = right;\n const keys = Object.keys(left);\n if (keys.length !== Object.keys(other).length)\n return false;\n for (const key of keys)\n if (!Object.hasOwn(other, key) || !equalTrustedJson(left[key], other[key]))\n return false;\n return true;\n }\n function abortContext(context2) {\n if (context2.status.value === \"aborted\" || context2.status.value === \"consumed\" || context2.status.value === \"stale\")\n return;\n context2.status.value = \"aborted\";\n clearContext(context2);\n }\n function releaseOverlayReferences(context2) {\n context2.tracker.deref()?.releaseContext(context2);\n if (locatedDenseArray?.context === context2)\n locatedDenseArray = void 0;\n context2.overlayReleased = true;\n context2.dirty.length = 0;\n context2.nodes.length = 0;\n context2.rawNodes = void 0;\n context2.ops = void 0;\n context2.root = void 0;\n context2.bases = void 0;\n context2.stored = void 0;\n context2.baseValue = void 0;\n }\n function clearContext(context2) {\n context2.tracker.deref()?.releaseContext(context2);\n if (locatedDenseArray?.context === context2)\n locatedDenseArray = void 0;\n for (const node of context2.nodes) {\n if (Array.isArray(node.target))\n node.target.length = 0;\n Reflect.deleteProperty(node.target, NODE);\n node.writes?.clear();\n node.deletes?.clear();\n node.readded?.clear();\n if (node.array?.pieces !== void 0)\n node.array.pieces.length = 0;\n if (node.array !== void 0) {\n node.array.root = void 0;\n node.array.baseLocations = void 0;\n node.array.insertLocations = void 0;\n }\n node.array?.baseOverrides?.clear();\n node.array?.insertOverrides?.clear();\n node.parentSource = void 0;\n node.target = RELEASED;\n node.proxy = RELEASED;\n node.writeKey = void 0;\n node.writeValue = void 0;\n node.writes = void 0;\n node.deleteKey = void 0;\n node.deletes = void 0;\n node.readded = void 0;\n node.array = void 0;\n node.subtreeDirty = void 0;\n node.preparedPath = void 0;\n }\n context2.dirty.length = 0;\n context2.nodes.length = 0;\n context2.rawNodes = void 0;\n context2.ops = void 0;\n context2.root = void 0;\n context2.bases = void 0;\n context2.stored = void 0;\n context2.baseValue = void 0;\n context2.overlayReleased = true;\n }\n function isContainer2(value) {\n return value !== null && typeof value === \"object\";\n }\n\n // node_modules/@earendil-works/chord/dist/delta/index.js\n var isObj = (value) => value !== null && typeof value === \"object\";\n function overlap(a, b, scan, probe = 64, maxCandidates = 8) {\n if (a.length === 0 || b.length === 0 || scan === 0)\n return 0;\n const tail = a.length > scan ? a.slice(a.length - scan) : a;\n for (const h of [Math.min(probe, b.length), 1]) {\n const head = b.slice(0, h);\n let tried = 0;\n for (let k = tail.indexOf(head); k !== -1; k = tail.indexOf(head, k + 1)) {\n if (++tried > maxCandidates)\n break;\n const n = tail.length - k;\n if (n <= b.length && tail.slice(k) === b.slice(0, n))\n return n;\n }\n if (h === 1)\n break;\n }\n return 0;\n }\n var RESERVED_SEGMENTS = /* @__PURE__ */ new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n var UnsafePathError = class extends Error {\n // Not a parameter property: Node's --experimental-strip-types rejects those,\n // and these files are meant to run under it directly.\n segment;\n constructor(segment) {\n super(`unsafe path segment: ${String(segment)}`);\n this.segment = segment;\n this.name = \"UnsafePathError\";\n }\n };\n function assertValidOp(op) {\n if (!Array.isArray(op) || op.length === 0)\n throw new TypeError(\"op is not a tuple\");\n switch (op[0]) {\n case \"r\":\n if (op.length !== 2)\n throw new TypeError(\"r arity\");\n return;\n case \"s\":\n if (op.length !== 3)\n throw new TypeError(\"s arity\");\n assertPathArg(op[1], true);\n return;\n case \"d\":\n if (op.length !== 2)\n throw new TypeError(\"d arity\");\n assertPathArg(op[1], true);\n return;\n case \"a\":\n if (op.length !== 3 || typeof op[2] !== \"string\")\n throw new TypeError(\"a shape\");\n assertPathArg(op[1], true);\n return;\n case \"t\":\n if (op.length !== 3 || !Number.isInteger(op[2]) || op[2] < 0)\n throw new TypeError(\"t shape\");\n assertPathArg(op[1], true);\n return;\n case \"p\": {\n if (op.length !== 5)\n throw new TypeError(\"p arity\");\n assertPathArg(op[1]);\n if (!Number.isInteger(op[2]) || op[2] < 0)\n throw new TypeError(\"p index\");\n if (!Number.isInteger(op[3]) || op[3] < 0)\n throw new TypeError(\"p remove\");\n if (!Array.isArray(op[4]))\n throw new TypeError(\"p items\");\n return;\n }\n case \"m\":\n if (op.length !== 3)\n throw new TypeError(\"m arity\");\n assertPathArg(op[1]);\n assertPermutation(op[2]);\n return;\n // Silently skipping an unknown verb is how a newer producer's op vanishes.\n default:\n throw new TypeError(`unknown op verb: ${String(op[0])}`);\n }\n }\n function assertPathArg(p, nonEmpty = false) {\n if (!Array.isArray(p))\n throw new TypeError(\"path is not an array\");\n if (nonEmpty && p.length === 0)\n throw new TypeError(\"path is empty\");\n assertSafePath(p);\n }\n function assertPermutation(value) {\n if (!Array.isArray(value))\n throw new TypeError(\"m permutation is not an array\");\n const seen = new Uint8Array(value.length);\n for (const index3 of value) {\n if (!Number.isInteger(index3) || index3 < 0 || index3 >= value.length || seen[index3] !== 0) {\n throw new TypeError(\"m permutation is not a bijection\");\n }\n seen[index3] = 1;\n }\n }\n function assertSafePath(path) {\n for (const seg of path) {\n if (typeof seg === \"string\") {\n if (RESERVED_SEGMENTS.has(seg))\n throw new UnsafePathError(seg);\n } else if (!Number.isInteger(seg) || seg < 0) {\n throw new UnsafePathError(seg);\n }\n }\n }\n function assertIndexInRange(parent, index3) {\n if (index3 > parent.length)\n throw new UnsafePathError(index3);\n }\n var PathError = class extends Error {\n path;\n constructor(path) {\n super(`unresolvable path: ${JSON.stringify(path)}`);\n this.path = path;\n this.name = \"PathError\";\n }\n };\n function applyOps(target, ops) {\n let root2 = target;\n for (const op of ops) {\n assertValidOp(op);\n if (op[0] === \"r\") {\n root2 = op[1];\n continue;\n }\n const path = op[1];\n assertSafePath(path);\n if (op[0] === \"p\") {\n const target_ = path.length === 0 ? root2 : resolve(root2, path);\n if (!Array.isArray(target_))\n throw new PathError(path);\n target_.splice(op[2], op[3]);\n const chunkSize = 1e4;\n for (let offset = 0; offset < op[4].length; offset += chunkSize) {\n target_.splice(op[2] + offset, 0, ...op[4].slice(offset, offset + chunkSize));\n }\n continue;\n }\n if (op[0] === \"m\") {\n const target_ = path.length === 0 ? root2 : resolve(root2, path);\n if (!Array.isArray(target_) || target_.length !== op[2].length)\n throw new PathError(path);\n const previous = target_.slice();\n for (let index3 = 0; index3 < op[2].length; index3++)\n target_[index3] = previous[op[2][index3]];\n continue;\n }\n const parent = resolve(root2, path.slice(0, -1));\n const key = path[path.length - 1];\n if (Array.isArray(parent)) {\n if (typeof key !== \"number\")\n throw new UnsafePathError(key);\n assertIndexInRange(parent, key);\n }\n const write = (value) => {\n Object.defineProperty(parent, key, { value, writable: true, enumerable: true, configurable: true });\n };\n const read2 = () => Object.hasOwn(parent, key) ? parent[key] : void 0;\n switch (op[0]) {\n case \"s\":\n write(op[2]);\n break;\n case \"d\":\n if (Array.isArray(parent)) {\n if (typeof key !== \"number\" || key >= parent.length)\n throw new PathError(path);\n parent.splice(key, 1);\n } else\n delete parent[key];\n break;\n case \"a\": {\n const current = read2();\n if (typeof current !== \"string\")\n throw new PathError(path);\n write(`${current}${op[2]}`);\n break;\n }\n case \"t\": {\n const current = read2();\n if (typeof current !== \"string\")\n throw new PathError(path);\n write(current.slice(op[2]));\n break;\n }\n }\n }\n return root2;\n }\n function applyImmutable(target, ops) {\n return applyImmutableBatches(target, [ops]);\n }\n function applyImmutableBatches(target, batches) {\n let root2 = target;\n const owned = /* @__PURE__ */ new WeakSet();\n for (const ops of batches) {\n for (const op of ops) {\n assertValidOp(op);\n if (op[0] === \"r\") {\n root2 = op[1];\n continue;\n }\n root2 = copyContainers(root2, op[0] === \"p\" || op[0] === \"m\" ? op[1] : op[1].slice(0, -1), owned);\n root2 = applyOps(root2, [op]);\n }\n }\n return root2;\n }\n function copyContainers(root2, path, owned) {\n const copy2 = (value) => {\n if (Array.isArray(value))\n return value.slice();\n if (!isObj(value))\n throw new PathError(path);\n const result = Object.create(Object.getPrototypeOf(value) === null ? null : Object.prototype);\n for (const key of Object.keys(value)) {\n Object.defineProperty(result, key, {\n value: value[key],\n writable: true,\n enumerable: true,\n configurable: true\n });\n }\n return result;\n };\n if (!isObj(root2))\n throw new PathError(path);\n let copiedRoot;\n if (owned.has(root2))\n copiedRoot = root2;\n else {\n copiedRoot = copy2(root2);\n owned.add(copiedRoot);\n }\n let destination = copiedRoot;\n for (const segment of path) {\n if (!Object.hasOwn(destination, segment))\n throw new PathError(path);\n if (Array.isArray(destination) && typeof segment !== \"number\")\n throw new UnsafePathError(segment);\n const child = destination[segment];\n if (!isObj(child))\n throw new PathError(path);\n if (owned.has(child)) {\n destination = child;\n continue;\n }\n const copiedChild = copy2(child);\n Object.defineProperty(destination, segment, {\n value: copiedChild,\n writable: true,\n enumerable: true,\n configurable: true\n });\n owned.add(copiedChild);\n destination = copiedChild;\n }\n return copiedRoot;\n }\n function resolveValue(root2, path) {\n let node = root2;\n for (const seg of path) {\n if (!isObj(node))\n throw new PathError(path);\n if (Array.isArray(node) && typeof seg !== \"number\")\n throw new UnsafePathError(seg);\n if (!Object.hasOwn(node, seg))\n throw new PathError(path);\n node = node[seg];\n }\n return node;\n }\n function resolve(root2, path) {\n const node = resolveValue(root2, path);\n if (!isObj(node))\n throw new PathError(path);\n return node;\n }\n\n // node_modules/@earendil-works/chord/dist/services/state-internals.js\n var sources = /* @__PURE__ */ new WeakMap();\n function registerReplicatedStateInternals(value, internals) {\n sources.set(value, internals);\n }\n\n // node_modules/@earendil-works/chord/dist/services/state.js\n var StateSubscriber = class {\n #listener;\n #reportError;\n #pending = [];\n #running = false;\n #started = false;\n #closed = false;\n constructor(listener, reportError) {\n this.#listener = listener;\n this.#reportError = reportError;\n }\n push(frame) {\n if (this.#closed)\n return;\n if (this.#pending.length === 100) {\n const hydration = this.#started ? void 0 : this.#pending[0];\n this.#pending.length = 0;\n if (hydration !== void 0)\n this.#pending.push(hydration);\n }\n this.#pending.push(frame);\n }\n drain() {\n if (this.#running || this.#closed)\n return;\n this.#running = true;\n for (let frame = this.#pending.shift(); frame !== void 0; frame = this.#pending.shift()) {\n this.#started = true;\n try {\n const result = this.#listener(frame.value, frame.context, frame.delivery);\n if (isPromiseLike(result)) {\n void Promise.resolve(result).then(() => this.#resume(), (error) => {\n this.#report(error);\n this.#resume();\n });\n return;\n }\n } catch (error) {\n this.#report(error);\n }\n }\n this.#running = false;\n }\n clear() {\n this.#pending.length = 0;\n }\n close() {\n this.#closed = true;\n this.clear();\n }\n #resume() {\n this.#running = false;\n this.drain();\n }\n #report(error) {\n try {\n this.#reportError(toError(error));\n } catch (reportError) {\n reportErrorAsync(toError(reportError));\n }\n }\n };\n var ReplicatedStatePublisher = class {\n #listeners = /* @__PURE__ */ new Map();\n #reportError;\n #sourceListeners = /* @__PURE__ */ new Set();\n #publications = [];\n #value;\n #sequence = 0;\n #delivering = false;\n constructor(initial, reportError = reportErrorAsync) {\n this.#value = initial;\n this.#reportError = reportError;\n }\n get value() {\n return this.#value;\n }\n snapshot() {\n return { value: this.#value, sequence: this.#sequence };\n }\n subscribe(listener) {\n const { value, sequence: sequence2 } = this.snapshot();\n const subscriber = new StateSubscriber(listener, this.#reportError);\n this.#listeners.set(subscriber, sequence2);\n subscriber.push({ value, context: serviceDeliveryContext(), delivery: { kind: \"hydrate\", sequence: sequence2 } });\n subscriber.drain();\n return () => {\n subscriber.close();\n this.#listeners.delete(subscriber);\n };\n }\n subscribeSource(listener) {\n this.#sourceListeners.add(listener);\n return () => this.#sourceListeners.delete(listener);\n }\n /** Publish an already-prepared immutable revision and return isolated listener failures. */\n publish(value, ops, context2) {\n this.#value = value;\n this.#sequence += 1;\n this.#publications.push({ value, ops, sequence: this.#sequence, context: context2 });\n if (this.#delivering)\n return [];\n this.#delivering = true;\n const errors = [];\n try {\n for (let publication = this.#publications.shift(); publication !== void 0; publication = this.#publications.shift()) {\n for (const listener of [...this.#sourceListeners]) {\n try {\n listener(publication.ops, publication.sequence, publication.context);\n } catch (error) {\n errors.push(error);\n }\n }\n const delivery = { kind: \"update\", sequence: publication.sequence };\n for (const [subscriber, hydratedSequence] of [...this.#listeners]) {\n if (publication.sequence <= hydratedSequence)\n continue;\n subscriber.push({ value: publication.value, context: publication.context, delivery });\n subscriber.drain();\n }\n }\n } finally {\n this.#delivering = false;\n }\n return errors;\n }\n };\n var MutableReplicatedStateImpl = class {\n #tracker;\n #publisher;\n #changing = false;\n constructor(initial) {\n this.#tracker = track(initial);\n this.#publisher = new ReplicatedStatePublisher(this.#tracker.value);\n registerReplicatedStateInternals(this, {\n snapshot: () => this.#publisher.snapshot(),\n subscribe: (listener) => this.#publisher.subscribeSource(listener)\n });\n }\n get value() {\n return this.#tracker.value;\n }\n change(context2, mutate) {\n if (this.#changing)\n throw new Error(\"Replicated state cannot be changed reentrantly from a change callback\");\n this.#changing = true;\n let prepared;\n try {\n const change = this.#tracker.beginChange();\n try {\n const outcome = mutate(change.state);\n if (isPromiseLike(outcome)) {\n void Promise.resolve(outcome).catch(() => void 0);\n throw new TypeError(\"Replicated state change callbacks must be synchronous\");\n }\n prepared = change.prepare();\n } catch (error) {\n change.abort();\n throw error;\n }\n } finally {\n this.#changing = false;\n }\n this.#tracker.adopt(prepared);\n if (prepared.ops.length === 0)\n return;\n throwCollectedErrors(this.#publisher.publish(prepared.value, prepared.ops, context2), \"Replicated state listeners failed\");\n }\n replace(context2, value) {\n if (this.#changing)\n throw new Error(\"Replicated state cannot be replaced from a change callback\");\n const prepared = this.#tracker.prepareReplace(value);\n this.#tracker.adopt(prepared);\n if (prepared.ops.length === 0)\n return;\n throwCollectedErrors(this.#publisher.publish(prepared.value, prepared.ops, context2), \"Replicated state listeners failed\");\n }\n subscribe(listener) {\n return this.#publisher.subscribe(listener);\n }\n };\n var AttachedReplicatedStateImpl = class {\n #publisher;\n #attachment;\n #reportError;\n #cursor;\n #disposed = false;\n constructor(attachment, options) {\n const { snapshot } = attachment;\n assertCursor(snapshot.cursor, \"snapshot\");\n this.#attachment = attachment;\n this.#cursor = snapshot.cursor;\n this.#reportError = options.onError ?? reportErrorAsync;\n this.#publisher = new ReplicatedStatePublisher(snapshot.value, (error) => this.#report(error));\n registerReplicatedStateInternals(this, {\n snapshot: () => this.#publisher.snapshot(),\n subscribe: (listener) => this.#publisher.subscribeSource(listener)\n });\n }\n get value() {\n return this.#publisher.value;\n }\n subscribe(listener) {\n return this.#publisher.subscribe(listener);\n }\n activate() {\n this.#attachment.activate((frame) => this.#receive(frame));\n }\n dispose() {\n if (this.#disposed)\n return;\n this.#disposed = true;\n this.#attachment.dispose();\n }\n #receive(frame) {\n if (this.#disposed)\n return;\n try {\n assertCursor(frame.cursor, \"frame\");\n const expected = this.#cursor + 1;\n if (frame.cursor !== expected) {\n throw new Error(`Replicated state source cursor has a gap: expected ${expected}, received ${frame.cursor}`);\n }\n this.#cursor = frame.cursor;\n const errors = this.#publisher.publish(frame.value, frame.ops, frame.context);\n if (errors.length === 1)\n this.#report(errors[0]);\n else if (errors.length > 1)\n this.#report(new AggregateError(errors, \"Replicated state listeners failed\"));\n } catch (error) {\n this.#fail(toError(error));\n }\n }\n #fail(error) {\n if (this.#disposed)\n return;\n this.#disposed = true;\n try {\n this.#attachment.dispose();\n } catch (disposeError) {\n this.#report(new AggregateError([error, disposeError], \"Replicated state source contract failed\"));\n return;\n }\n this.#report(error);\n }\n #report(error) {\n try {\n this.#reportError(toError(error));\n } catch (reportError) {\n reportErrorAsync(toError(reportError));\n }\n }\n };\n function attachReplicatedStateSource(source, options = {}) {\n const attachment = source.attach();\n try {\n const state2 = new AttachedReplicatedStateImpl(attachment, options);\n state2.activate();\n return state2;\n } catch (error) {\n try {\n attachment.dispose();\n } catch (disposeError) {\n throw new AggregateError([error, disposeError], \"Failed to attach replicated state source\");\n }\n throw error;\n }\n }\n function serviceDeliveryContext() {\n return BACKGROUND_CONTEXT;\n }\n function assertCursor(cursor, kind) {\n if (!Number.isSafeInteger(cursor))\n throw new TypeError(`Replicated state source ${kind} cursor must be a safe integer`);\n }\n function isPromiseLike(value) {\n return (typeof value === \"object\" && value !== null || typeof value === \"function\") && typeof value.then === \"function\";\n }\n function throwCollectedErrors(errors, message) {\n if (errors.length === 1)\n throw errors[0];\n if (errors.length > 1)\n throw new AggregateError(errors, message);\n }\n function reportErrorAsync(error) {\n queueMicrotask(() => {\n throw error;\n });\n }\n function toError(error) {\n return error instanceof Error ? error : new Error(String(error));\n }\n\n // node_modules/@earendil-works/chord/dist/api.js\n function replicatedState(initialOrSource, options) {\n if (isReplicatedStateSource(initialOrSource))\n return attachReplicatedStateSource(initialOrSource, options);\n return new MutableReplicatedStateImpl(initialOrSource);\n }\n function isReplicatedStateSource(value) {\n return typeof value.attach === \"function\";\n }\n\n // node_modules/@earendil-works/pi-durable/dist/ids.js\n function idFromNumber(value) {\n return value;\n }\n function seqFromNumber(value) {\n return value;\n }\n\n // node_modules/@earendil-works/pi-durable/dist/documents.js\n function defineDoc(definition) {\n validateDefinition(definition);\n return { definition };\n }\n function defineDocFamily(definition) {\n validateDefinition(definition);\n return { definition };\n }\n function validateDefinition(definition) {\n if (!Number.isSafeInteger(definition.version) || definition.version < 1) {\n throw new TypeError(`Document ${definition.kind} version must be a positive integer`);\n }\n }\n function resolveAddress(definition, args) {\n let index3 = 0;\n let scope;\n switch (definition.scope) {\n case \"session\":\n scope = { kind: \"session\" };\n break;\n case \"conversation\":\n scope = { kind: \"conversation\", conversationId: ownerId(args[index3++], definition) };\n break;\n case \"task\":\n scope = { kind: \"task\", taskId: ownerId(args[index3++], definition) };\n break;\n }\n const key = definition.family === true ? args[index3++] : void 0;\n const address = key === void 0 ? { kind: definition.kind, scope } : { kind: definition.kind, scope, key };\n return { address, id: addressId(address), nextArgument: index3 };\n }\n function ownerId(value, definition) {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value)) {\n throw new TypeError(`Document ${definition.kind} requires a ${definition.scope} ID`);\n }\n return idFromNumber(value);\n }\n function addressId(address) {\n const owner = address.scope.kind === \"session\" ? null : address.scope.kind === \"conversation\" ? address.scope.conversationId : address.scope.taskId;\n return JSON.stringify([address.kind, address.scope.kind, owner, address.key ?? null]);\n }\n function documentCreate(definition, address, id) {\n const key = address.key === void 0 ? {} : { key: address.key };\n switch (address.scope.kind) {\n case \"session\":\n return { id, kind: address.kind, ...key, scope: address.scope };\n case \"task\":\n return { id, kind: address.kind, ...key, scope: address.scope };\n case \"conversation\":\n return {\n id,\n kind: address.kind,\n ...key,\n scope: address.scope,\n history: definition.history,\n fork: definition.fork\n };\n }\n }\n function checkRecordScope(definition, record) {\n if (record.scope.kind !== definition.scope || record.scope.kind === \"conversation\" && (record.history !== definition.history || record.fork !== definition.fork)) {\n throw new TypeError(`Document ${record.id} (${record.kind}) does not match the supplied definition semantics`);\n }\n }\n function checkRecordVersion(definition, record, version) {\n if (version > definition.version) {\n throw new Error(`Document ${record.id} (${record.kind}) has newer version ${version} than ${definition.version}`);\n }\n if (version < definition.version && definition.migrate === void 0) {\n throw new Error(`Document ${record.id} (${record.kind}) requires migration from version ${version}`);\n }\n }\n function materializeDocument(definition, stored) {\n return materializeDocumentValue(definition, stored.record, stored.version, stored.value);\n }\n function materializeDocumentValue(definition, record, version, value) {\n checkRecordScope(definition, record);\n checkRecordVersion(definition, record, version);\n if (version === definition.version)\n return value;\n return copyJson(definition.migrate(value, version));\n }\n\n // node_modules/@earendil-works/pi-durable/dist/entries.js\n function defineEntry(kind) {\n if (typeof kind !== \"string\" || kind.length === 0)\n throw new TypeError(\"Entry kind must be a non-empty string\");\n return {\n kind,\n is: (entry) => entry !== void 0 && entry.kind === kind\n };\n }\n var UserEntry = defineEntry(\"pi.user\");\n var AssistantEntry = defineEntry(\"pi.assistant\");\n var SystemEntry = defineEntry(\"pi.system\");\n var ToolResultEntry = defineEntry(\"pi.tool-result\");\n var ResetEntry = defineEntry(\"pi.reset\");\n var CompactionEntry = defineEntry(\"pi.compaction\");\n\n // node_modules/@earendil-works/pi-durable/dist/errors.js\n var ReadAfterWrite = class extends Error {\n constructor(method) {\n super(`Tx.${method}() cannot read tables after the first table write`);\n this.name = \"ReadAfterWrite\";\n }\n };\n var StorageRejected = class extends Error {\n constructor(message, options) {\n super(message, options);\n this.name = \"StorageRejected\";\n }\n };\n var ConversationBusy = class extends Error {\n conversationId;\n constructor(conversationId) {\n super(`Conversation ${conversationId} is busy`);\n this.name = \"ConversationBusy\";\n this.conversationId = conversationId;\n }\n };\n\n // node_modules/@earendil-works/pi-durable/dist/harness/agent.js\n var DEFAULT_RETRY_POLICY = {\n enabled: true,\n maxRetries: 3,\n baseDelayMs: 2e3,\n maxAgentDelayMs: 6e4\n };\n var DEFAULT_COMPACTION_POLICY = {\n enabled: true,\n reserveTokens: 16384,\n keepRecentTokens: 2e4,\n backgroundTokens: 32768\n };\n var DEFAULT_PROGRESS_POLICY = {\n partialIntervalMs: 100,\n outputIntervalMs: 100\n };\n var INSTRUCTIONS_KEY = \"instructions\";\n var AgentDoc = defineDoc({\n kind: \"pi.agent\",\n version: 1,\n scope: \"conversation\",\n history: \"rewindable\",\n fork: \"asOf\",\n initial: () => ({}),\n checkpointWhen: () => true\n });\n var DEFAULT_CONTEXT_RETENTION_MS = 6e5;\n function resolveSettings(settings2) {\n const extensions = settings2?.extensions;\n return {\n ...extensions === void 0 ? {} : { extensions },\n stream: { ...settings2?.stream },\n retry: { ...DEFAULT_RETRY_POLICY, ...settings2?.retry },\n compaction: { ...DEFAULT_COMPACTION_POLICY, ...settings2?.compaction },\n // Field by field, so an explicitly undefined interval keeps its default.\n progress: {\n partialIntervalMs: settings2?.progress?.partialIntervalMs ?? DEFAULT_PROGRESS_POLICY.partialIntervalMs,\n outputIntervalMs: settings2?.progress?.outputIntervalMs ?? DEFAULT_PROGRESS_POLICY.outputIntervalMs\n },\n toolExecution: settings2?.toolExecution ?? \"parallel\",\n steeringMode: settings2?.steeringMode ?? \"one-at-a-time\",\n followUpMode: settings2?.followUpMode ?? \"one-at-a-time\",\n contextRetentionMs: settings2?.contextRetentionMs ?? DEFAULT_CONTEXT_RETENTION_MS\n };\n }\n async function configure(tx, conversationId, change) {\n const state2 = await tx.doc(AgentDoc, conversationId);\n applyChange(state2, change);\n }\n async function addTools(tx, conversationId, added) {\n const state2 = await tx.doc(AgentDoc, conversationId);\n const tools = state2.tools;\n if (tools === void 0)\n return;\n if (Array.isArray(tools)) {\n for (const name of added)\n if (!tools.includes(name))\n tools.push(name);\n } else {\n const remove = tools.remove;\n if (remove.some((name) => added.includes(name))) {\n state2.tools = { remove: remove.filter((name) => !added.includes(name)) };\n }\n }\n }\n function applyChange(state2, change) {\n const set = (key, value) => {\n if (value === void 0)\n return;\n if (value === null)\n delete state2[key];\n else\n state2[key] = value;\n };\n set(\"model\", change.model === void 0 || change.model === null ? change.model : { ...change.model });\n set(\"thinkingLevel\", change.thinkingLevel);\n const extensions = change.extensions;\n set(\"extensions\", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : {\n ...extensions.add === void 0 ? {} : { add: names(extensions.add) },\n ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) }\n });\n const tools = change.tools;\n set(\"tools\", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) });\n set(\"instructions\", change.instructions);\n set(\"cwd\", change.cwd);\n }\n function isList(value) {\n return Array.isArray(value);\n }\n function names(items) {\n return items.map((item) => item.name);\n }\n async function createAgent(tx, conversation2) {\n if (conversation2.parent !== void 0)\n return;\n const agent = await tx.doc(AgentDoc, conversation2.id);\n if (conversation2.owner === void 0)\n return;\n const owner = await tx.doc(AgentDoc, conversation2.owner.conversationId);\n Object.assign(agent, copyJson(owner));\n }\n function agentHooks(agent, taskName) {\n const handlers = [];\n for (const extension of agent.extensions) {\n for (const hook2 of extension.hooks ?? [])\n if (hook2.task === taskName)\n handlers.push(hook2.handlers);\n }\n return handlers;\n }\n function resolveAgent(state2, snapshot, settings2, report) {\n const extensions = selectExtensions(state2?.extensions, snapshot, settings2);\n const composed = /* @__PURE__ */ new Map();\n for (const extension of extensions)\n for (const tool of extension.tools ?? [])\n composed.set(tool.name, tool);\n const sections = /* @__PURE__ */ new Map();\n for (const extension of extensions) {\n for (const section2 of extension.sections ?? [])\n sections.set(section2.key, section2);\n }\n for (const extension of extensions) {\n for (const wrap of extension.wraps ?? []) {\n if (\"tool\" in wrap)\n applyWrap(composed, wrap.tool, (tool) => wrap.wrap(tool), (tool) => tool.name, report);\n else\n applyWrap(sections, wrap.section, (section2) => wrap.wrap(section2), (section2) => section2.key, report);\n }\n }\n const filter = state2?.tools;\n let tools;\n if (filter === void 0)\n tools = [...composed.values()];\n else if (Array.isArray(filter)) {\n tools = [];\n for (const name of new Set(filter)) {\n const tool = composed.get(name);\n if (tool !== void 0)\n tools.push(tool);\n }\n } else {\n const removed = new Set(filter.remove);\n tools = [...composed.values()].filter((tool) => !removed.has(tool.name));\n }\n const instructions = state2?.instructions;\n const agentSections = [...sections.values()];\n if (instructions !== void 0)\n agentSections.push({ key: INSTRUCTIONS_KEY, render: () => instructions });\n const agent = {\n ...state2?.model === void 0 ? {} : { model: state2.model },\n thinkingLevel: state2?.thinkingLevel ?? \"off\",\n extensions,\n tools,\n sections: agentSections,\n ...instructions === void 0 ? {} : { instructions },\n ...state2?.cwd === void 0 ? {} : { cwd: state2.cwd }\n };\n return agent;\n }\n function selectExtensions(stored, snapshot, settings2) {\n let selected;\n if (Array.isArray(stored))\n selected = stored;\n else {\n const base = settings2.extensions?.map((extension) => extension.name) ?? snapshot.installed().map((e) => e.name);\n const edit = stored;\n const removed = new Set(edit?.remove ?? []);\n selected = [...base, ...edit?.add ?? []].filter((name) => !removed.has(name));\n }\n const extensions = [];\n for (const name of new Set(selected)) {\n const extension = snapshot.extension(name);\n if (extension !== void 0)\n extensions.push(extension);\n }\n return extensions;\n }\n function applyWrap(items, target, wrap, nameOf, report) {\n const item = items.get(target);\n if (item === void 0)\n return;\n try {\n const wrapped = wrap(item);\n if (nameOf(wrapped) !== target)\n throw new Error(`Wrapper renamed ${target} to ${nameOf(wrapped)}`);\n items.set(target, wrapped);\n } catch (error) {\n items.delete(target);\n report(error);\n }\n }\n\n // node_modules/@earendil-works/pi-ai/dist/utils/text.js\n function contentText(content, separator = \"\\n\") {\n if (typeof content === \"string\")\n return content;\n return content.filter((block) => block.type === \"text\").map((block) => block.text).join(separator);\n }\n function getSystemMessageText(message) {\n const parts2 = [contentText(message.content)];\n for (const text of Object.values(message.sections ?? {})) {\n if (text !== null)\n parts2.push(text);\n }\n return parts2.filter((part) => part.length > 0).join(\"\\n\\n\");\n }\n\n // node_modules/@earendil-works/pi-ai/dist/utils/estimate.js\n var CHARS_PER_TOKEN = 3.5;\n var ESTIMATED_IMAGE_CHARS = 4800;\n function calculateContextTokens(usage2) {\n return usage2.totalTokens || usage2.input + usage2.output + usage2.cacheRead + usage2.cacheWrite;\n }\n function safeJsonStringify(value) {\n try {\n return JSON.stringify(value) ?? \"undefined\";\n } catch {\n return \"[unserializable]\";\n }\n }\n function estimateTextAndImageContentChars(content) {\n if (typeof content === \"string\")\n return content.length;\n let chars = 0;\n for (const block of content)\n chars += block.type === \"text\" ? block.text.length : ESTIMATED_IMAGE_CHARS;\n return chars;\n }\n function estimateTextTokens(text) {\n return Math.ceil(text.length / CHARS_PER_TOKEN);\n }\n function estimateTextAndImageContentTokens(content) {\n return Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN);\n }\n function estimateMessageTokens(message) {\n let chars = 0;\n if (message.role === \"system\") {\n return estimateTextTokens(getSystemMessageText(message)) + estimateToolsTokens(message.toolsAdded) + estimateToolsTokens(message.toolsRemoved);\n }\n if (message.role === \"user\")\n return estimateTextAndImageContentTokens(message.content);\n if (message.role === \"toolResult\")\n return estimateTextAndImageContentTokens(message.content);\n for (const block of message.content) {\n if (block.type === \"text\") {\n chars += block.text.length;\n } else if (block.type === \"thinking\") {\n chars += block.thinking.length;\n } else {\n chars += block.name.length + safeJsonStringify(block.arguments).length;\n }\n }\n return Math.ceil(chars / CHARS_PER_TOKEN);\n }\n function estimateToolsTokens(tools) {\n if (!tools || tools.length === 0)\n return 0;\n return estimateTextTokens(safeJsonStringify(tools));\n }\n\n // node_modules/@earendil-works/pi-ai/dist/utils/retry.js\n function buildProviderErrorPattern(patterns) {\n return new RegExp(patterns.join(\"|\"), \"i\");\n }\n var NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([\n // OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n // Zen API. These are subscription/account limits, not transient throttles.\n \"GoUsageLimitError\",\n \"FreeUsageLimitError\",\n // OpenCode Go subscription-limit text asks users to enable available-balance\n // usage after rolling/weekly/monthly limits are reached.\n \"Monthly usage limit reached\",\n \"available balance\",\n // Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n // quota/billing error code; the other strings cover common gateway wording.\n \"insufficient_quota\",\n \"out of budget\",\n \"quota exceeded\",\n \"billing\",\n // Sign in with ChatGPT: the subscription's shared usage limit, which resets\n // after hours rather than seconds.\n \"subscription_sharing_usage_limit_exceeded\"\n ]);\n var RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n // Generic provider load, HTTP status, and server-side transient failures.\n \"overloaded\",\n \"server_busy\",\n \"servers are currently busy\",\n \"currently experiencing high demand\",\n \"model is at capacity\",\n \"rate.?limit\",\n \"too many requests\",\n \"429\",\n \"500\",\n \"502\",\n \"503\",\n \"504\",\n \"520\",\n \"524\",\n \"service.?unavailable\",\n \"server.?error\",\n \"internal.?error\",\n // Wrapper/provider text for transient upstream failures, including OpenRouter\n // \"Provider returned error\" responses (#2264).\n \"provider.?returned.?error\",\n \"exceeded request buffer limit while retrying upstream\",\n // Network, proxy, and fetch transport failures. This includes OpenAI Codex\n // raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n // \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n \"network.?error\",\n \"connection.?error\",\n \"connection.?refused\",\n \"connection.?lost\",\n \"other side closed\",\n \"fetch failed\",\n \"getaddrinfo\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n \"upstream.?connect\",\n \"reset before headers\",\n \"socket hang up\",\n \"socket connection was closed\",\n \"timed? out\",\n \"timeout\",\n \"terminated\",\n // WebSocket transports can report close/error text instead of HTTP/fetch text.\n \"websocket.?closed\",\n \"websocket.?error\",\n // Premature stream endings from SDKs and transports. Anthropic can throw\n // \"stream ended without ...\" and \"Anthropic stream ended before message_stop\"\n // (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).\n \"ended without\",\n \"stream ended before message_stop\",\n \"stream ended before a terminal response event\",\n \"http2 request did not get a response\",\n // Node ERR_HTTP2_STREAM_CANCEL: the HTTP/2 session died before the request was\n // sent, e.g. after the Bedrock SDK's 5-minute session timeout (#10379).\n \"pending stream has been canceled\",\n // Provider-requested retry delay cap failures should flow through the outer\n // retry policy so callers can surface/abort the backoff (#1123).\n \"retry delay\",\n // Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock\n // stream exceptions (#6019).\n \"you can retry your request\",\n \"try your request again\",\n \"please retry your request\",\n // gRPC based providers (e.g. NVIDIA NIM)\n \"ResourceExhausted\",\n // Sign in with ChatGPT: usage or user data temporarily unavailable. Usage\n // failures can arrive mid-stream without an HTTP 503 in the message.\n \"subscription_sharing_usage_unavailable\",\n \"subscription_sharing_user_unavailable\"\n ]);\n var DEFAULT_MAX_AGENT_RETRY_DELAY_MS = 6e4;\n function retryDelayMs(policy, attempt) {\n const delay2 = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);\n const safeDelay = Number.isSafeInteger(delay2) ? delay2 : Number.MAX_SAFE_INTEGER;\n return Math.min(safeDelay, policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\n }\n function isRetryableAssistantError(message) {\n if (message.stopReason !== \"error\" || !message.errorMessage)\n return false;\n const errorMessage = message.errorMessage;\n if (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage))\n return false;\n return RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);\n }\n\n // node_modules/@earendil-works/pi-durable/dist/tasks.js\n function defineTask(definition) {\n return { definition };\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/context.js\n var SCAN_PAGE_SIZE = 256;\n var EXCLUDED_STOP_REASONS = /* @__PURE__ */ new Set([\"aborted\", \"error\", \"deferred\"]);\n var MISSING_RESULT_TEXT = \"Tool result unavailable: history ends before this call completed.\";\n async function captureContextBounds(storage, conversationId, context2, at) {\n let tail;\n if (at === void 0) {\n tail = (await storage.scanEntries({ conversationId }, 1, void 0, context2)).items[0]?.id;\n if (tail === void 0)\n return void 0;\n } else {\n if (await storage.entry(conversationId, at, context2) === void 0) {\n throw new Error(`Entry ${at} is not visible from conversation ${conversationId}`);\n }\n tail = at;\n }\n return { head: await storage.findLatestHeadMarker(conversationId, tail, context2), tail };\n }\n async function readContextFrom(session, storage, conversationId, context2, at, previous) {\n const bounds = await session.readOnLine(() => captureContextBounds(storage, conversationId, context2, at));\n if (bounds === void 0)\n return { view: emptyView(), range: void 0 };\n freezeJson(bounds.head);\n let range;\n if (previous === void 0 || previous.bounds.head?.id !== bounds.head?.id) {\n range = deriveRange(bounds, freezeJson(await scanRange(storage, conversationId, rangeQuery(bounds), context2)));\n } else if (bounds.tail === previous.bounds.tail) {\n range = previous;\n } else if (bounds.tail < previous.bounds.tail) {\n range = deriveRange(bounds, previous.entries.filter((entry) => entry.id <= bounds.tail));\n } else {\n const minEntryId = idFromNumber(previous.bounds.tail + 1);\n const added = await scanRange(storage, conversationId, { minEntryId, maxEntryId: bounds.tail }, context2);\n range = extendRange(previous, bounds, freezeJson(added));\n }\n const { view } = range;\n return {\n view: {\n ...view,\n entries: [...view.entries],\n contributions: [...view.contributions],\n messages: [...view.messages]\n },\n range\n };\n }\n async function readContext(session, storage, conversationId, context2, at) {\n const bounds = await session.readOnLine(() => captureContextBounds(storage, conversationId, context2, at));\n return deriveContext(storage, conversationId, bounds, context2);\n }\n async function deriveContext(storage, conversationId, bounds, context2) {\n if (bounds === void 0)\n return emptyView();\n return deriveRange(bounds, await scanRange(storage, conversationId, rangeQuery(bounds), context2)).view;\n }\n function emptyView() {\n return { head: void 0, entries: [], contributions: [], messages: [] };\n }\n function deriveRange(bounds, entries) {\n const edits = /* @__PURE__ */ new Map();\n for (const entry of entries)\n for (const edit of entry.edits ?? [])\n edits.set(edit.target, edit);\n const active = selectActive(bounds.head, entries);\n const contributions = active.map((entry) => contribute(entry, edits.get(entry.id)));\n const { settled, open: open2 } = settle([], contributions.flat());\n const messages = leadWithSystem([...settled, ...orderToolResults(open2)]);\n const view = { head: bounds.head, entries: active, contributions, messages };\n return { bounds, entries, view, edited: new Set(edits.keys()), settled, open: open2 };\n }\n function extendRange(previous, bounds, added) {\n const entries = [...previous.entries, ...added];\n if (added.some((entry) => entry.edits !== void 0 || entry.head !== void 0 || previous.edited.has(entry.id))) {\n return deriveRange(bounds, entries);\n }\n const contributions = added.map((entry) => contribute(entry, void 0));\n const { settled, open: open2 } = settle(previous.settled, [...previous.open, ...contributions.flat()]);\n const view = {\n head: bounds.head,\n entries: [...previous.view.entries, ...added],\n contributions: [...previous.view.contributions, ...contributions],\n messages: leadWithSystem([...settled, ...orderToolResults(open2)])\n };\n return { bounds, entries, view, edited: previous.edited, settled, open: open2 };\n }\n function leadWithSystem(messages) {\n const index3 = messages.findIndex((message) => message.role !== \"user\");\n if (index3 <= 0 || messages[index3].role !== \"system\")\n return messages;\n return [messages[index3], ...messages.slice(0, index3), ...messages.slice(index3 + 1)];\n }\n function contribute(entry, edit) {\n if (edit?.action === \"omit\")\n return Object.freeze([]);\n const contributed = edit?.action === \"replace\" ? edit.messages : entry.model ?? [];\n return Object.freeze(contributed.filter((message) => message.role !== \"assistant\" || !EXCLUDED_STOP_REASONS.has(message.stopReason)));\n }\n var deeplyFrozen = /* @__PURE__ */ new WeakSet();\n function freezeJson(value) {\n if (value === null || typeof value !== \"object\" || deeplyFrozen.has(value))\n return value;\n for (const child of Object.values(value))\n freezeJson(child);\n Object.freeze(value);\n deeplyFrozen.add(value);\n return value;\n }\n function settle(settled, open2) {\n const last = open2.findLastIndex((message) => message.role === \"assistant\");\n if (last <= 0)\n return { settled, open: open2 };\n return { settled: [...settled, ...orderToolResults(open2.slice(0, last))], open: open2.slice(last) };\n }\n async function activeEntries(storage, conversationId, bounds, context2) {\n if (bounds === void 0)\n return [];\n return selectActive(bounds.head, await scanRange(storage, conversationId, rangeQuery(bounds), context2));\n }\n function rangeQuery(bounds) {\n const head = bounds.head;\n return head === void 0 ? { maxEntryId: bounds.tail } : { minEntryId: head.head, maxEntryId: bounds.tail };\n }\n async function scanRange(storage, conversationId, range, context2) {\n const entries = [];\n let cursor;\n do {\n const page2 = await storage.scanEntries({ conversationId, ...range }, SCAN_PAGE_SIZE, cursor, context2);\n entries.push(...page2.items);\n cursor = page2.next;\n } while (cursor !== void 0);\n return entries.reverse();\n }\n function selectActive(head, range) {\n return head === void 0 ? range : [head, ...range.filter((entry) => entry.head === void 0)];\n }\n function orderToolResults(messages) {\n const ordered = [];\n for (let index3 = 0; index3 < messages.length; index3++) {\n const message = messages[index3];\n if (message.role === \"toolResult\")\n continue;\n ordered.push(message);\n if (message.role !== \"assistant\")\n continue;\n const calls = message.content.filter((content) => content.type === \"toolCall\");\n if (calls.length === 0)\n continue;\n const results = /* @__PURE__ */ new Map();\n for (let next = index3 + 1; next < messages.length && messages[next].role !== \"assistant\"; next++) {\n const candidate = messages[next];\n if (candidate.role === \"toolResult\" && !results.has(candidate.toolCallId)) {\n results.set(candidate.toolCallId, next);\n }\n }\n for (const call of calls) {\n const resultIndex = results.get(call.id);\n ordered.push(resultIndex === void 0 ? missingResult(call, message.timestamp) : messages[resultIndex]);\n }\n }\n return ordered;\n }\n function missingResult(call, timestamp) {\n return freezeJson({\n role: \"toolResult\",\n toolCallId: call.id,\n toolName: call.name,\n content: [{ type: \"text\", text: MISSING_RESULT_TEXT }],\n isError: true,\n details: { reason: \"missing_result\" },\n timestamp\n });\n }\n\n // node_modules/@earendil-works/pi-ai/dist/utils/overflow.js\n var OVERFLOW_PATTERNS = [\n /prompt (?:is )?too long/i,\n // Anthropic and z.ai token overflow\n /prompt exceeds max length/i,\n // z.ai CN endpoint token overflow\n /request_too_large/i,\n // Anthropic request byte-size overflow (HTTP 413)\n /input is too long for requested model/i,\n // Amazon Bedrock\n /exceeds the context window/i,\n // OpenAI (Completions & Responses API)\n /exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\\d,]+ tokens?|\\s*\\([\\d,]+\\))/i,\n // OpenAI-compatible proxies (LiteLLM)\n /input token count.*exceeds the maximum/i,\n // Google (Gemini)\n /maximum prompt length is \\d+/i,\n // xAI (Grok)\n /reduce the length of the messages/i,\n // Groq\n /maximum context length is \\d+ tokens/i,\n // OpenRouter (most backends)\n /exceeds (?:the )?maximum allowed input length of [\\d,]+ tokens?/i,\n // OpenRouter/Poolside\n /input \\(\\d+ tokens\\) is longer than the model'?s context length \\(\\d+ tokens\\)/i,\n // Together AI\n /exceeds the limit of \\d+/i,\n // GitHub Copilot\n /exceeds the available context size/i,\n // llama.cpp server\n /greater than the context length/i,\n // LM Studio\n /context window exceeds limit/i,\n // MiniMax\n /exceeded model token limit/i,\n // Kimi For Coding\n /too large for model with \\d+ maximum context length/i,\n // Mistral\n /prompt has [\\d,]+ tokens?, but the configured context size is [\\d,]+ tokens?/i,\n // DS4 server\n /model_context_window_exceeded/i,\n // z.ai non-standard finish_reason surfaced as error text\n /prompt too long; exceeded (?:max )?context length/i,\n // Ollama explicit overflow error\n /range of input length should be/i,\n // DashScope / Qwen Token Plan\n /context[_ ]length[_ ]exceeded/i,\n // Generic fallback\n /too many tokens/i,\n // Generic fallback\n /token limit exceeded/i\n // Generic fallback\n ];\n var CEREBRAS_BODYLESS_OVERFLOW_PATTERN = /^4(?:00|13)\\s*(?:status code)?\\s*\\(no body\\)/i;\n var NON_OVERFLOW_PATTERNS = [\n /^(Throttling error|Service unavailable):/i,\n // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError)\n /rate limit/i,\n // Generic rate limiting\n /too many requests/i\n // Generic HTTP 429 style\n ];\n function isContextOverflow(message, contextWindow) {\n if (message.stopReason === \"error\" && message.errorMessage) {\n const isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage));\n if (!isNonOverflow) {\n if (OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage))) {\n return true;\n }\n if (message.provider === \"cerebras\" && CEREBRAS_BODYLESS_OVERFLOW_PATTERN.test(message.errorMessage)) {\n return true;\n }\n }\n }\n if (contextWindow && message.stopReason === \"stop\") {\n const inputTokens = message.usage.input + message.usage.cacheRead;\n if (inputTokens > contextWindow) {\n return true;\n }\n }\n if (contextWindow && message.stopReason === \"length\" && message.usage.output === 0) {\n const inputTokens = message.usage.input + message.usage.cacheRead;\n if (inputTokens >= contextWindow * 0.99) {\n return true;\n }\n }\n return false;\n }\n\n // node_modules/@earendil-works/pi-ai/dist/utils/transcript.js\n function createInitialSystemMessage(systemPrompt, tools) {\n const hasSystemPrompt = systemPrompt !== void 0 && systemPrompt.length > 0;\n const hasTools = tools !== void 0 && tools.length > 0;\n if (!hasSystemPrompt && !hasTools)\n return void 0;\n return {\n role: \"system\",\n content: systemPrompt ?? \"\",\n ...hasTools ? { toolsAdded: tools } : {},\n timestamp: 0\n };\n }\n function normalizeContext(context2) {\n const initialMessage = createInitialSystemMessage(context2.systemPrompt, context2.tools);\n const messages = initialMessage ? [initialMessage, ...context2.messages] : context2.messages;\n return { messages };\n }\n function isSystemMessage(message) {\n return message.role === \"system\";\n }\n function getCurrentTools(messages) {\n const tools = /* @__PURE__ */ new Map();\n for (const message of messages) {\n if (!isSystemMessage(message))\n continue;\n for (const tool of message.toolsRemoved ?? [])\n tools.delete(tool.name);\n for (const tool of message.toolsAdded ?? [])\n tools.set(tool.name, tool);\n }\n return [...tools.values()];\n }\n function toToolDeclaration(tool) {\n return {\n name: tool.name,\n description: tool.description,\n parameters: JSON.parse(JSON.stringify(tool.parameters)),\n ...tool.constrainedSampling === void 0 ? {} : { constrainedSampling: tool.constrainedSampling }\n };\n }\n function declarationsEqual(left, right) {\n return JSON.stringify(toToolDeclaration(left)) === JSON.stringify(toToolDeclaration(right));\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/inbox.js\n var InboxDoc = defineDoc({\n kind: \"pi.inbox\",\n version: 1,\n scope: \"conversation\",\n history: \"latest\",\n fork: \"initial\",\n initial: () => ({ items: [] }),\n checkpointWhen: (value) => value.items.length === 0\n });\n async function prepareBoundary(tx, conversationId, modes) {\n const head = (await tx.latestHeadMarker(conversationId))?.head;\n const inbox = await tx.doc(InboxDoc, conversationId);\n return {\n conversationId,\n inbox,\n steeringMode: modes.steeringMode,\n followUpMode: modes.followUpMode,\n head\n };\n }\n async function applyBoundary(tx, boundary, at, now) {\n const { conversationId, inbox } = boundary;\n const items = inbox.items;\n const reset = items.some((item) => item.mode === \"write\" && item.entry.head === \"self\");\n const final = at === \"final\" || reset;\n const pick = (mode, queueMode) => {\n const indexes = items.flatMap((item, index3) => item.mode === mode ? [index3] : []);\n return queueMode === \"all\" ? indexes : indexes.slice(0, 1);\n };\n const writes = items.flatMap((item, index3) => item.mode === \"write\" ? [index3] : []);\n const users = [...pick(\"steer\", boundary.steeringMode), ...final ? pick(\"followUp\", boundary.followUpMode) : []];\n users.sort((a, b) => a - b);\n for (const index3 of writes) {\n const item = items[index3];\n const draft = item.entry;\n if (isStale(boundary, draft)) {\n tx.settleSubmission(item.id, { status: \"unanswered\", reason: \"stale\" });\n continue;\n }\n const entry = await tx.appendEntry(conversationId, draft);\n if (draft.head !== void 0)\n boundary.head = draft.head === \"self\" ? entry.id : draft.head;\n tx.placeSubmission(item.id, entry.id);\n }\n const placed = [];\n for (const index3 of users) {\n const item = items[index3];\n const message = { role: \"user\", content: item.content, timestamp: now };\n const entry = await tx.appendEntry(UserEntry, conversationId, { model: [message] });\n tx.placeSubmission(item.id, entry.id);\n placed.push(item.id);\n }\n const removed = [...writes, ...users].sort((a, b) => b - a);\n for (const index3 of removed)\n items.splice(index3, 1);\n return { users: placed, reset };\n }\n function isStale(boundary, entry) {\n return typeof entry.head === \"number\" && boundary.head !== void 0 && entry.head < boundary.head;\n }\n async function removeInboxItem(tx, conversationId, id) {\n const items = (await tx.doc(InboxDoc, conversationId)).items;\n const index3 = items.findIndex((item) => item.id === id);\n if (index3 >= 0)\n items.splice(index3, 1);\n }\n async function withdrawQueuedInputs(tx, conversationId) {\n const items = (await tx.doc(InboxDoc, conversationId)).items;\n for (let index3 = items.length - 1; index3 >= 0; index3--) {\n const item = items[index3];\n if (item.mode === \"write\")\n continue;\n tx.settleSubmission(item.id, { status: \"unanswered\", reason: \"aborted\" });\n items.splice(index3, 1);\n }\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/json.js\n function assignJson(target, key, value) {\n const slots = target;\n const current = slots[key];\n if (isRecord(current) && isRecord(value)) {\n for (const name of Object.keys(current))\n if (!Object.hasOwn(value, name))\n delete current[name];\n for (const [name, child] of Object.entries(value))\n assignJson(current, name, child);\n return;\n }\n if (Array.isArray(current) && Array.isArray(value) && current.length <= value.length) {\n const items = current;\n for (let index3 = 0; index3 < value.length; index3++) {\n if (index3 < items.length)\n assignJson(items, index3, value[index3]);\n else\n items.push(value[index3]);\n }\n return;\n }\n if (current !== value)\n slots[key] = value;\n }\n function isRecord(value) {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/prompt.js\n function replaySections(messages) {\n const shown = /* @__PURE__ */ new Map();\n for (const message of messages) {\n if (message.role !== \"system\" || message.sections === void 0)\n continue;\n for (const [key, value] of Object.entries(message.sections)) {\n if (value === null)\n shown.delete(key);\n else\n shown.set(key, value);\n }\n }\n return shown;\n }\n async function renderSections(sections, input, shown, report, context2) {\n const desired = /* @__PURE__ */ new Map();\n for (const section2 of sections) {\n let text;\n try {\n text = await section2.render(input, context2);\n } catch (error) {\n if (context2.abortSignal?.aborted)\n throw error;\n report(error);\n const kept = shown.get(section2.key);\n if (kept !== void 0)\n desired.set(section2.key, kept);\n continue;\n }\n if (text === void 0)\n continue;\n desired.set(section2.key, section2.tag === false ? text : `<${section2.key}>\n${text}\n</${section2.key}>`);\n }\n return desired;\n }\n function planSystemEntries(view, desired, tools, timestamp) {\n const head = view.head;\n if (head !== void 0 && !view.entries.some((entry) => SystemEntry.is(entry) && entry.id > head.id)) {\n const edits = view.entries.filter((entry) => SystemEntry.is(entry)).map((entry) => ({ target: entry.id, action: \"omit\" }));\n const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp);\n return [edits.length === 0 ? baseline : { ...baseline, edits }];\n }\n const sections = planSections(replaySections(view.messages), desired);\n const changes = planTools(getCurrentTools(view.messages), tools);\n if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) {\n return sections.map((patch) => systemEntry(patch, void 0, timestamp));\n }\n if (sections.length === 0)\n return [systemEntry(void 0, changes, timestamp)];\n return sections.map((patch, index3) => systemEntry(patch, index3 === sections.length - 1 ? changes : void 0, timestamp));\n }\n function planTools(offered, desired) {\n const wanted = new Map(desired.map((tool) => [tool.name, tool]));\n const kept = offered.filter((tool) => {\n const next = wanted.get(tool.name);\n return next !== void 0 && declarationsEqual(tool, next);\n });\n const keptNames = new Set(kept.map((tool) => tool.name));\n const added = desired.filter((tool) => !keptNames.has(tool.name));\n const replayed = [...kept, ...added];\n if (replayed.some((tool, index3) => tool.name !== desired[index3].name)) {\n return {\n toolsRemoved: offered.map((tool) => ({ name: tool.name })),\n toolsAdded: desired.map(toToolDeclaration)\n };\n }\n return {\n toolsRemoved: offered.filter((tool) => !keptNames.has(tool.name)).map((tool) => ({ name: tool.name })),\n toolsAdded: added.map(toToolDeclaration)\n };\n }\n function planSections(shown, desired) {\n const patchedOrder = [\n ...[...shown.keys()].filter((key) => desired.has(key)),\n ...[...desired.keys()].filter((key) => !shown.has(key))\n ];\n const desiredOrder = [...desired.keys()];\n if (patchedOrder.some((key, index3) => key !== desiredOrder[index3])) {\n return [Object.fromEntries([...shown.keys()].map((key) => [key, null])), Object.fromEntries(desired)];\n }\n const patch = {};\n for (const [key, value] of shown) {\n const next = desired.get(key);\n if (next !== value)\n patch[key] = next ?? null;\n }\n for (const [key, value] of desired)\n if (!shown.has(key))\n patch[key] = value;\n return Object.keys(patch).length === 0 ? [] : [patch];\n }\n function systemEntry(sections, tools, timestamp) {\n const message = {\n role: \"system\",\n content: \"\",\n ...sections === void 0 ? {} : { sections },\n ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved },\n ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded },\n timestamp\n };\n return { model: [message] };\n }\n\n // node_modules/@earendil-works/pi-ai/dist/utils/uuid.js\n var MAX_UUID_V7_TIMESTAMP = 281474976710655;\n var MAX_SEQUENCE = (1n << 41n) - 1n;\n var lastOrdinaryTimestamp = -1;\n var sequence;\n function uuidv7(timestampMs) {\n const requestedTimestamp = timestampMs ?? Date.now();\n if (!Number.isInteger(requestedTimestamp) || requestedTimestamp < 0 || requestedTimestamp > MAX_UUID_V7_TIMESTAMP) {\n throw new RangeError(`UUIDv7 timestamp must be an integer between 0 and ${MAX_UUID_V7_TIMESTAMP}`);\n }\n const effectiveTimestamp = timestampMs === void 0 ? Math.max(requestedTimestamp, lastOrdinaryTimestamp) : timestampMs;\n if (timestampMs === void 0)\n lastOrdinaryTimestamp = effectiveTimestamp;\n const bytes = new Uint8Array(16);\n globalThis.crypto.getRandomValues(bytes);\n if (sequence === void 0) {\n sequence = BigInt(bytes[1]) << 32n | BigInt(bytes[2]) << 24n | BigInt(bytes[3]) << 16n | BigInt(bytes[4]) << 8n | BigInt(bytes[5]);\n } else {\n if (sequence === MAX_SEQUENCE)\n throw new RangeError(\"UUIDv7 generator sequence exhausted\");\n sequence++;\n }\n const timestamp = BigInt(effectiveTimestamp);\n for (let index3 = 5; index3 >= 0; index3--) {\n bytes[index3] = Number(timestamp >> BigInt((5 - index3) * 8)) & 255;\n }\n bytes[6] = 112 | Number(sequence >> 37n & 0x0fn);\n bytes[7] = Number(sequence >> 29n & 0xffn);\n bytes[8] = 128 | Number(sequence >> 23n & 0x3fn);\n bytes[9] = Number(sequence >> 15n & 0xffn);\n bytes[10] = Number(sequence >> 7n & 0xffn);\n bytes[11] = Number((sequence & 0x7fn) << 1n) | bytes[11] & 1;\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\"));\n return `${hex.slice(0, 4).join(\"\")}-${hex.slice(4, 6).join(\"\")}-${hex.slice(6, 8).join(\"\")}-${hex.slice(8, 10).join(\"\")}-${hex.slice(10).join(\"\")}`;\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/provider.js\n var ProviderDoc = defineDoc({\n kind: \"pi.provider\",\n version: 1,\n scope: \"conversation\",\n history: \"latest\",\n fork: \"initial\",\n initial: () => ({ sessionId: uuidv7() }),\n checkpointWhen: () => true\n });\n async function ensureProviderSessionId(runtime, context2) {\n const existing = await runtime.snapshot(ProviderDoc, runtime.conversationId, context2);\n if (existing !== void 0)\n return existing.sessionId;\n let created;\n await runtime.commit(async (tx) => {\n created = (await tx.doc(ProviderDoc, runtime.conversationId)).sessionId;\n return void 0;\n }, context2);\n if (created === void 0)\n throw new Error(`Conversation ${runtime.conversationId} has no provider session ID`);\n return created;\n }\n\n // node_modules/typebox/build/system/arguments/arguments.mjs\n var arguments_exports = {};\n __export(arguments_exports, {\n Match: () => Match\n });\n function Match(args, match) {\n return match[args.length]?.(...args) ?? (() => {\n throw Error(\"Invalid Arguments\");\n })();\n }\n\n // node_modules/typebox/build/system/settings/settings.mjs\n var settings_exports = {};\n __export(settings_exports, {\n Get: () => Get,\n Reset: () => Reset,\n Set: () => Set2\n });\n\n // node_modules/typebox/build/guard/emit.mjs\n var emit_exports = {};\n __export(emit_exports, {\n And: () => And,\n ArrayLiteral: () => ArrayLiteral,\n ArrowFunction: () => ArrowFunction,\n Call: () => Call,\n ConstDeclaration: () => ConstDeclaration,\n Constant: () => Constant,\n Counted: () => Counted2,\n Entries: () => Entries2,\n Every: () => Every2,\n HasPropertyKey: () => HasPropertyKey2,\n If: () => If,\n IsArray: () => IsArray2,\n IsBigInt: () => IsBigInt2,\n IsBoolean: () => IsBoolean2,\n IsConstructor: () => IsConstructor2,\n IsDeepEqual: () => IsDeepEqual2,\n IsEqual: () => IsEqual2,\n IsFunction: () => IsFunction2,\n IsGreaterEqualThan: () => IsGreaterEqualThan2,\n IsGreaterThan: () => IsGreaterThan2,\n IsInteger: () => IsInteger2,\n IsLessEqualThan: () => IsLessEqualThan2,\n IsLessThan: () => IsLessThan2,\n IsMaxLength: () => IsMaxLength3,\n IsMinLength: () => IsMinLength3,\n IsNull: () => IsNull2,\n IsNumber: () => IsNumber2,\n IsObject: () => IsObject2,\n IsObjectNotArray: () => IsObjectNotArray2,\n IsString: () => IsString2,\n IsSymbol: () => IsSymbol2,\n IsUndefined: () => IsUndefined2,\n Keys: () => Keys2,\n Member: () => Member,\n MultipleOf: () => MultipleOf,\n New: () => New,\n Not: () => Not,\n Or: () => Or,\n ReduceAnd: () => ReduceAnd,\n ReduceOr: () => ReduceOr,\n Return: () => Return,\n Some: () => Some2,\n SomeAll: () => SomeAll2,\n Statements: () => Statements,\n Ternary: () => Ternary\n });\n\n // node_modules/typebox/build/guard/guard.mjs\n var guard_exports = {};\n __export(guard_exports, {\n Counted: () => Counted,\n Entries: () => Entries,\n EntriesRegExp: () => EntriesRegExp,\n Every: () => Every,\n EveryAll: () => EveryAll,\n GraphemeCount: () => GraphemeCount2,\n HasPropertyKey: () => HasPropertyKey,\n IsArray: () => IsArray,\n IsBigInt: () => IsBigInt,\n IsBoolean: () => IsBoolean,\n IsClassInstance: () => IsClassInstance,\n IsConstructor: () => IsConstructor,\n IsDeepEqual: () => IsDeepEqual,\n IsEqual: () => IsEqual,\n IsFunction: () => IsFunction,\n IsGreaterEqualThan: () => IsGreaterEqualThan,\n IsGreaterThan: () => IsGreaterThan,\n IsInteger: () => IsInteger,\n IsLessEqualThan: () => IsLessEqualThan,\n IsLessThan: () => IsLessThan,\n IsMaxLength: () => IsMaxLength2,\n IsMinLength: () => IsMinLength2,\n IsMultipleOf: () => IsMultipleOf,\n IsNull: () => IsNull,\n IsNumber: () => IsNumber,\n IsObject: () => IsObject,\n IsObjectNotArray: () => IsObjectNotArray,\n IsString: () => IsString,\n IsSymbol: () => IsSymbol,\n IsUndefined: () => IsUndefined,\n IsUnsafePropertyKey: () => IsUnsafePropertyKey,\n IsValueLike: () => IsValueLike,\n Keys: () => Keys,\n ShiftLeft: () => ShiftLeft,\n Some: () => Some,\n SomeAll: () => SomeAll,\n Symbols: () => Symbols,\n Values: () => Values\n });\n\n // node_modules/typebox/build/guard/string.mjs\n function IsBetween(value, min, max) {\n return value >= min && value <= max;\n }\n function IsZeroWidthJoiner(value) {\n return value === 8205;\n }\n function IsHighSurrogate(value) {\n return IsBetween(value, 55296, 56319);\n }\n function IsRegionalIndicator(value) {\n return IsBetween(value, 127462, 127487);\n }\n function IsVariationSelector(value) {\n return IsBetween(value, 65024, 65039);\n }\n function IsCombiningMark(value) {\n return IsBetween(value, 768, 879) || IsBetween(value, 6832, 6911) || IsBetween(value, 7616, 7679) || IsBetween(value, 65056, 65071);\n }\n function CodePointLength(value) {\n return value > 65535 ? 2 : 1;\n }\n function ConsumeModifiers(value, index3) {\n while (index3 < value.length) {\n const point = value.codePointAt(index3);\n if (IsCombiningMark(point) || IsVariationSelector(point)) {\n index3 += CodePointLength(point);\n } else {\n break;\n }\n }\n return index3;\n }\n function NextGraphemeClusterIndex(value, clusterStart) {\n const startCP = value.codePointAt(clusterStart);\n let clusterEnd = clusterStart + CodePointLength(startCP);\n clusterEnd = ConsumeModifiers(value, clusterEnd);\n while (clusterEnd < value.length - 1 && IsZeroWidthJoiner(value.codePointAt(clusterEnd))) {\n const nextCP = value.codePointAt(clusterEnd + 1);\n clusterEnd += 1 + CodePointLength(nextCP);\n clusterEnd = ConsumeModifiers(value, clusterEnd);\n }\n if (IsRegionalIndicator(startCP) && clusterEnd < value.length && IsRegionalIndicator(value.codePointAt(clusterEnd))) {\n clusterEnd += CodePointLength(value.codePointAt(clusterEnd));\n }\n return clusterEnd;\n }\n function IsGraphemeCodePoint(value) {\n return value >= 768 && // above special range\n (IsHighSurrogate(value) || IsCombiningMark(value) || IsVariationSelector(value) || IsZeroWidthJoiner(value));\n }\n function GraphemeCount(value) {\n let count = 0;\n let index3 = 0;\n while (index3 < value.length) {\n index3 = NextGraphemeClusterIndex(value, index3);\n count++;\n }\n return count;\n }\n function IsMinLengthSegmented(value, minLength) {\n let count = 0;\n let index3 = 0;\n while (index3 < value.length) {\n index3 = NextGraphemeClusterIndex(value, index3);\n if (++count >= minLength)\n return true;\n }\n return false;\n }\n function IsMaxLengthSegmented(value, maxLength) {\n let count = 0;\n let index3 = 0;\n while (index3 < value.length) {\n index3 = NextGraphemeClusterIndex(value, index3);\n if (++count > maxLength)\n return false;\n }\n return true;\n }\n function IsMinLength(value, minLength) {\n if (minLength === 0)\n return true;\n if (value.length < minLength)\n return false;\n let index3 = 0;\n while (true) {\n if (IsGraphemeCodePoint(value.charCodeAt(index3))) {\n return IsMinLengthSegmented(value, minLength);\n }\n if (++index3 >= minLength)\n return true;\n }\n }\n function IsMaxLength(value, maxLength) {\n if (value.length <= maxLength)\n return true;\n let index3 = 0;\n while (true) {\n if (IsGraphemeCodePoint(value.charCodeAt(index3))) {\n return IsMaxLengthSegmented(value, maxLength);\n }\n if (++index3 > maxLength)\n return false;\n }\n }\n\n // node_modules/typebox/build/guard/guard.mjs\n function IsArray(value) {\n return Array.isArray(value);\n }\n function IsBigInt(value) {\n return IsEqual(typeof value, \"bigint\");\n }\n function IsBoolean(value) {\n return IsEqual(typeof value, \"boolean\");\n }\n function IsConstructor(value) {\n if (IsUndefined(value) || !IsFunction(value))\n return false;\n const result = Function.prototype.toString.call(value);\n if (/^class\\s/.test(result))\n return true;\n if (/\\[native code\\]/.test(result))\n return true;\n return false;\n }\n function IsFunction(value) {\n return IsEqual(typeof value, \"function\");\n }\n function IsInteger(value) {\n return Number.isInteger(value);\n }\n function IsNull(value) {\n return IsEqual(value, null);\n }\n function IsNumber(value) {\n return Number.isFinite(value);\n }\n function IsObjectNotArray(value) {\n return IsObject(value) && !IsArray(value);\n }\n function IsObject(value) {\n return IsEqual(typeof value, \"object\") && !IsNull(value);\n }\n function IsString(value) {\n return IsEqual(typeof value, \"string\");\n }\n function IsSymbol(value) {\n return IsEqual(typeof value, \"symbol\");\n }\n function IsUndefined(value) {\n return IsEqual(value, void 0);\n }\n function IsEqual(left, right) {\n return left === right;\n }\n function IsGreaterThan(left, right) {\n return left > right;\n }\n function IsLessThan(left, right) {\n return left < right;\n }\n function IsLessEqualThan(left, right) {\n return left <= right;\n }\n function IsGreaterEqualThan(left, right) {\n return left >= right;\n }\n function IsMultipleOf(dividend, divisor) {\n if (IsBigInt(dividend) || IsBigInt(divisor)) {\n return BigInt(dividend) % BigInt(divisor) === 0n;\n }\n const tolerance = 1e-10;\n if (!IsNumber(dividend))\n return true;\n if (IsInteger(dividend) && 1 / divisor % 1 === 0)\n return true;\n const mod = dividend % divisor;\n return Math.min(Math.abs(mod), Math.abs(mod - divisor), Math.abs(mod + divisor)) < tolerance;\n }\n function IsClassInstance(value) {\n if (!IsObject(value))\n return false;\n const proto = globalThis.Object.getPrototypeOf(value);\n if (IsNull(proto))\n return false;\n return IsEqual(typeof proto.constructor, \"function\") && !(IsEqual(proto.constructor, globalThis.Object) || IsEqual(proto.constructor.name, \"Object\"));\n }\n function IsValueLike(value) {\n return IsBigInt(value) || IsBoolean(value) || IsNull(value) || IsNumber(value) || IsString(value) || IsUndefined(value);\n }\n function GraphemeCount2(value) {\n return GraphemeCount(value);\n }\n function IsMaxLength2(value, length) {\n return IsMaxLength(value, length);\n }\n function IsMinLength2(value, length) {\n return IsMinLength(value, length);\n }\n function Every(value, offset, callback) {\n return value.every((item, index3) => index3 < offset || callback(item, index3));\n }\n function EveryAll(value, offset, callback) {\n let result = true;\n value.forEach((item, index3) => {\n if (index3 >= offset && !callback(item, index3))\n result = false;\n });\n return result;\n }\n function Some(value, callback) {\n return value.some((value2, index3) => callback(value2, index3));\n }\n function SomeAll(value, callback) {\n let result = false;\n value.forEach((item, index3) => {\n if (callback(item, index3))\n result = true;\n });\n return result;\n }\n function Counted(value, callback) {\n return value.reduce((result, value2, index3) => callback(value2, index3) ? ++result : result, 0);\n }\n function ShiftLeft(array, true_, false_) {\n return IsEqual(array.length, 0) ? false_() : true_(array[0], array.slice(1));\n }\n function IsUnsafePropertyKey(key) {\n return IsEqual(key, \"__proto__\") || IsEqual(key, \"constructor\") || IsEqual(key, \"prototype\");\n }\n function HasPropertyKey(value, key) {\n return IsUnsafePropertyKey(key) ? Object.prototype.hasOwnProperty.call(value, key) : key in value;\n }\n function EntriesRegExp(value) {\n return Keys(value).map((key) => [new RegExp(`^${key}$`), value[key]]);\n }\n function Entries(value) {\n return Object.entries(value);\n }\n function Keys(value) {\n return Object.getOwnPropertyNames(value);\n }\n function Symbols(value) {\n return Object.getOwnPropertySymbols(value);\n }\n function Values(value) {\n return Object.values(value);\n }\n function DeepEqualObject(left, right) {\n if (!IsObject(right))\n return false;\n const keys = Keys(left);\n return IsEqual(keys.length, Keys(right).length) && keys.every((key) => IsDeepEqual(left[key], right[key]));\n }\n function DeepEqualArray(left, right) {\n return IsArray(right) && IsEqual(left.length, right.length) && left.every((_, index3) => IsDeepEqual(left[index3], right[index3]));\n }\n function IsDeepEqual(left, right) {\n return IsArray(left) ? DeepEqualArray(left, right) : IsObject(left) ? DeepEqualObject(left, right) : IsEqual(left, right);\n }\n\n // node_modules/typebox/build/guard/emit.mjs\n var identifierRegExp = /^[\\p{ID_Start}_$][\\p{ID_Continue}_$\\u200C\\u200D]*$/u;\n function IsIdentifier(value) {\n return identifierRegExp.test(value);\n }\n function And(left, right) {\n return `(${left} && ${right})`;\n }\n function Or(left, right) {\n return `(${left} || ${right})`;\n }\n function Not(expr) {\n return `!(${expr})`;\n }\n function IsArray2(value) {\n return `Array.isArray(${value})`;\n }\n function IsBigInt2(value) {\n return `typeof ${value} === \"bigint\"`;\n }\n function IsBoolean2(value) {\n return `typeof ${value} === \"boolean\"`;\n }\n function IsInteger2(value) {\n return `Number.isInteger(${value})`;\n }\n function IsNull2(value) {\n return `${value} === null`;\n }\n function IsNumber2(value) {\n return `Number.isFinite(${value})`;\n }\n function IsObjectNotArray2(value) {\n return And(IsObject2(value), Not(IsArray2(value)));\n }\n function IsObject2(value) {\n return `typeof ${value} === \"object\" && ${value} !== null`;\n }\n function IsString2(value) {\n return `typeof ${value} === \"string\"`;\n }\n function IsSymbol2(value) {\n return `typeof ${value} === \"symbol\"`;\n }\n function IsUndefined2(value) {\n return `${value} === undefined`;\n }\n function IsFunction2(value) {\n return `typeof ${value} === \"function\"`;\n }\n function IsConstructor2(value) {\n return `Guard.IsConstructor(${value})`;\n }\n function IsEqual2(left, right) {\n return `${left} === ${right}`;\n }\n function IsGreaterThan2(left, right) {\n return `${left} > ${right}`;\n }\n function IsLessThan2(left, right) {\n return `${left} < ${right}`;\n }\n function IsLessEqualThan2(left, right) {\n return `${left} <= ${right}`;\n }\n function IsGreaterEqualThan2(left, right) {\n return `${left} >= ${right}`;\n }\n function IsMinLength3(value, length) {\n return `Guard.IsMinLength(${value}, ${length})`;\n }\n function IsMaxLength3(value, length) {\n return `Guard.IsMaxLength(${value}, ${length})`;\n }\n function Every2(value, offset, params, expression) {\n return IsEqual(offset, \"0\") ? `${value}.every((${params[0]}, ${params[1]}) => (${expression}))` : `${value}.every((${params[0]}, ${params[1]}) => (${params[1]} < ${offset}) || (${expression}))`;\n }\n function Some2(value, params, expression) {\n return `${value}.some((${params[0]}, ${params[1]}) => ${expression})`;\n }\n function SomeAll2(value, params, expression) {\n return `((value) => { let result = false; value.forEach((${params[0]}, ${params[1]}) => { if (${expression}) result = true }); return result })(${value})`;\n }\n function Counted2(value, params, expression) {\n return `${value}.reduce((result, ${params[0]}, ${params[1]}) => (${expression}) ? ++result : result, 0)`;\n }\n function Entries2(value) {\n return `Object.entries(${value})`;\n }\n function Keys2(value) {\n return `Object.getOwnPropertyNames(${value})`;\n }\n function HasPropertyKey2(value, key) {\n const isProtoField = IsEqual(key, '\"__proto__\"') || IsEqual(key, '\"constructor\"');\n return isProtoField ? `Object.prototype.hasOwnProperty.call(${value}, ${key})` : `${key} in ${value}`;\n }\n function IsDeepEqual2(left, right) {\n return `Guard.IsDeepEqual(${left}, ${right})`;\n }\n function ArrayLiteral(elements) {\n return `[${elements.join(\", \")}]`;\n }\n function ArrowFunction(parameters, body) {\n return `((${parameters.join(\", \")}) => ${body})`;\n }\n function Call(value, arguments_) {\n return `${value}(${arguments_.join(\", \")})`;\n }\n function New(value, arguments_) {\n return `new ${value}(${arguments_.join(\", \")})`;\n }\n function Member(left, right) {\n return `${left}${IsIdentifier(right) ? `.${right}` : `[${Constant(right)}]`}`;\n }\n function Constant(value) {\n if (!IsValueLike(value))\n throw Error(\"Unsupported Constant\");\n return IsString(value) ? JSON.stringify(value) : `${value}`;\n }\n function Ternary(condition, true_, false_) {\n return `(${condition} ? ${true_} : ${false_})`;\n }\n function Statements(statements) {\n return `{ ${statements.join(\"; \")}; }`;\n }\n function ConstDeclaration(identifier, expression) {\n return `const ${identifier} = ${expression}`;\n }\n function If(condition, then) {\n return `if(${condition}) { ${then} }`;\n }\n function Return(expression) {\n return `return ${expression}`;\n }\n function ReduceAnd(operands) {\n return IsEqual(operands.length, 0) ? \"true\" : operands.reduce((left, right) => And(left, right));\n }\n function ReduceOr(operands) {\n return IsEqual(operands.length, 0) ? \"false\" : operands.reduce((left, right) => Or(left, right));\n }\n function MultipleOf(dividend, divisor) {\n return `Guard.IsMultipleOf(${dividend}, ${divisor})`;\n }\n\n // node_modules/typebox/build/guard/globals.mjs\n var globals_exports = {};\n __export(globals_exports, {\n IsBigInt64Array: () => IsBigInt64Array,\n IsBigUint64Array: () => IsBigUint64Array,\n IsBoolean: () => IsBoolean3,\n IsDate: () => IsDate,\n IsFloat32Array: () => IsFloat32Array,\n IsFloat64Array: () => IsFloat64Array,\n IsInt16Array: () => IsInt16Array,\n IsInt32Array: () => IsInt32Array,\n IsInt8Array: () => IsInt8Array,\n IsMap: () => IsMap,\n IsNumber: () => IsNumber3,\n IsRegExp: () => IsRegExp,\n IsSet: () => IsSet,\n IsString: () => IsString3,\n IsTypeArray: () => IsTypeArray,\n IsUint16Array: () => IsUint16Array,\n IsUint32Array: () => IsUint32Array,\n IsUint8Array: () => IsUint8Array,\n IsUint8ClampedArray: () => IsUint8ClampedArray\n });\n function IsBoolean3(value) {\n return value instanceof Boolean;\n }\n function IsNumber3(value) {\n return value instanceof Number;\n }\n function IsString3(value) {\n return value instanceof String;\n }\n function IsTypeArray(value) {\n return globalThis.ArrayBuffer.isView(value);\n }\n function IsInt8Array(value) {\n return value instanceof globalThis.Int8Array;\n }\n function IsUint8Array(value) {\n return value instanceof globalThis.Uint8Array;\n }\n function IsUint8ClampedArray(value) {\n return value instanceof globalThis.Uint8ClampedArray;\n }\n function IsInt16Array(value) {\n return value instanceof globalThis.Int16Array;\n }\n function IsUint16Array(value) {\n return value instanceof globalThis.Uint16Array;\n }\n function IsInt32Array(value) {\n return value instanceof globalThis.Int32Array;\n }\n function IsUint32Array(value) {\n return value instanceof globalThis.Uint32Array;\n }\n function IsFloat32Array(value) {\n return value instanceof globalThis.Float32Array;\n }\n function IsFloat64Array(value) {\n return value instanceof globalThis.Float64Array;\n }\n function IsBigInt64Array(value) {\n return value instanceof globalThis.BigInt64Array;\n }\n function IsBigUint64Array(value) {\n return value instanceof globalThis.BigUint64Array;\n }\n function IsRegExp(value) {\n return value instanceof globalThis.RegExp;\n }\n function IsDate(value) {\n return value instanceof globalThis.Date;\n }\n function IsSet(value) {\n return value instanceof globalThis.Set;\n }\n function IsMap(value) {\n return value instanceof globalThis.Map;\n }\n\n // node_modules/typebox/build/guard/index.mjs\n var guard_default = guard_exports;\n\n // node_modules/typebox/build/system/settings/settings.mjs\n var settings = {\n immutableTypes: false,\n maxErrors: 8,\n maxInstantiationCount: 128,\n useAcceleration: true,\n exactOptionalPropertyTypes: false,\n enumerableKind: false,\n correctiveParse: false,\n unionPrioritySort: true\n };\n function Reset() {\n settings.immutableTypes = false;\n settings.maxErrors = 8;\n settings.maxInstantiationCount = 128;\n settings.useAcceleration = true;\n settings.exactOptionalPropertyTypes = false;\n settings.enumerableKind = false;\n settings.correctiveParse = false;\n settings.unionPrioritySort = true;\n }\n function Set2(options) {\n for (const key of guard_exports.Keys(options)) {\n const value = options[key];\n if (value !== void 0) {\n Object.defineProperty(settings, key, { value });\n }\n }\n }\n function Get() {\n return settings;\n }\n\n // node_modules/typebox/build/schema/types/_refine.mjs\n function IsRefine(value) {\n return guard_exports.HasPropertyKey(value, \"~refine\") && guard_exports.IsArray(value[\"~refine\"]) && guard_exports.Every(value[\"~refine\"], 0, (value2) => guard_exports.IsObject(value2) && guard_exports.HasPropertyKey(value2, \"check\") && guard_exports.HasPropertyKey(value2, \"error\") && guard_exports.IsFunction(value2.check) && guard_exports.IsFunction(value2.error));\n }\n\n // node_modules/typebox/build/schema/types/schema.mjs\n function IsSchemaObject(value) {\n return guard_exports.IsObject(value) && !guard_exports.IsArray(value);\n }\n function IsSchemaBoolean(value) {\n return guard_exports.IsBoolean(value);\n }\n function IsSchema(value) {\n return IsSchemaObject(value) || IsSchemaBoolean(value);\n }\n\n // node_modules/typebox/build/schema/types/additionalItems.mjs\n function IsAdditionalItems(schema) {\n return guard_exports.HasPropertyKey(schema, \"additionalItems\") && IsSchema(schema.additionalItems);\n }\n\n // node_modules/typebox/build/schema/types/additionalProperties.mjs\n function IsAdditionalProperties(schema) {\n return guard_exports.HasPropertyKey(schema, \"additionalProperties\") && IsSchema(schema.additionalProperties);\n }\n\n // node_modules/typebox/build/schema/types/allOf.mjs\n function IsAllOf(schema) {\n return guard_exports.HasPropertyKey(schema, \"allOf\") && guard_exports.IsArray(schema.allOf) && schema.allOf.every((value) => IsSchema(value));\n }\n\n // node_modules/typebox/build/schema/types/anchor.mjs\n function IsAnchor(schema) {\n return guard_exports.HasPropertyKey(schema, \"$anchor\") && guard_exports.IsString(schema.$anchor);\n }\n\n // node_modules/typebox/build/schema/types/anyOf.mjs\n function IsAnyOf(schema) {\n return guard_exports.HasPropertyKey(schema, \"anyOf\") && guard_exports.IsArray(schema.anyOf) && schema.anyOf.every((value) => IsSchema(value));\n }\n\n // node_modules/typebox/build/schema/types/const.mjs\n function IsConst(value) {\n return guard_exports.HasPropertyKey(value, \"const\");\n }\n\n // node_modules/typebox/build/schema/types/contains.mjs\n function IsContains(schema) {\n return guard_exports.HasPropertyKey(schema, \"contains\") && IsSchema(schema.contains);\n }\n\n // node_modules/typebox/build/schema/types/default.mjs\n function IsDefault(schema) {\n return guard_exports.HasPropertyKey(schema, \"default\");\n }\n\n // node_modules/typebox/build/schema/types/dependencies.mjs\n function IsDependencies(schema) {\n return guard_exports.HasPropertyKey(schema, \"dependencies\") && guard_exports.IsObject(schema.dependencies) && Object.values(schema.dependencies).every((value) => IsSchema(value) || guard_exports.IsArray(value) && value.every((value2) => guard_exports.IsString(value2)));\n }\n\n // node_modules/typebox/build/schema/types/dependentRequired.mjs\n function IsDependentRequired(schema) {\n return guard_exports.HasPropertyKey(schema, \"dependentRequired\") && guard_exports.IsObject(schema.dependentRequired) && Object.values(schema.dependentRequired).every((value) => guard_exports.IsArray(value) && value.every((value2) => guard_exports.IsString(value2)));\n }\n\n // node_modules/typebox/build/schema/types/dependentSchemas.mjs\n function IsDependentSchemas(schema) {\n return guard_exports.HasPropertyKey(schema, \"dependentSchemas\") && guard_exports.IsObject(schema.dependentSchemas) && Object.values(schema.dependentSchemas).every((value) => IsSchema(value));\n }\n\n // node_modules/typebox/build/schema/types/dynamicAnchor.mjs\n function IsDynamicAnchor(schema) {\n return guard_exports.HasPropertyKey(schema, \"$dynamicAnchor\") && guard_exports.IsString(schema.$dynamicAnchor);\n }\n\n // node_modules/typebox/build/schema/types/dynamicRef.mjs\n function IsDynamicRef(schema) {\n return guard_exports.HasPropertyKey(schema, \"$dynamicRef\") && guard_exports.IsString(schema.$dynamicRef);\n }\n\n // node_modules/typebox/build/schema/types/else.mjs\n function IsElse(schema) {\n return guard_exports.HasPropertyKey(schema, \"else\") && IsSchema(schema.else);\n }\n\n // node_modules/typebox/build/schema/types/enum.mjs\n function IsEnum(schema) {\n return guard_exports.HasPropertyKey(schema, \"enum\") && guard_exports.IsArray(schema.enum);\n }\n\n // node_modules/typebox/build/schema/types/exclusiveMaximum.mjs\n function IsExclusiveMaximum(schema) {\n return guard_exports.HasPropertyKey(schema, \"exclusiveMaximum\") && (guard_exports.IsNumber(schema.exclusiveMaximum) || guard_exports.IsBigInt(schema.exclusiveMaximum));\n }\n\n // node_modules/typebox/build/schema/types/exclusiveMinimum.mjs\n function IsExclusiveMinimum(schema) {\n return guard_exports.HasPropertyKey(schema, \"exclusiveMinimum\") && (guard_exports.IsNumber(schema.exclusiveMinimum) || guard_exports.IsBigInt(schema.exclusiveMinimum));\n }\n\n // node_modules/typebox/build/schema/types/format.mjs\n function IsFormat(schema) {\n return guard_exports.HasPropertyKey(schema, \"format\") && guard_exports.IsString(schema.format);\n }\n\n // node_modules/typebox/build/schema/types/id.mjs\n function IsId(schema) {\n return guard_exports.HasPropertyKey(schema, \"$id\") && guard_exports.IsString(schema.$id);\n }\n\n // node_modules/typebox/build/schema/types/if.mjs\n function IsIf(schema) {\n return guard_exports.HasPropertyKey(schema, \"if\") && IsSchema(schema.if);\n }\n\n // node_modules/typebox/build/schema/types/items.mjs\n function IsItems(schema) {\n return guard_exports.HasPropertyKey(schema, \"items\") && (IsSchema(schema.items) || guard_exports.IsArray(schema.items) && schema.items.every((value) => {\n return IsSchema(value);\n }));\n }\n function IsItemsSized(schema) {\n return IsItems(schema) && guard_exports.IsArray(schema.items);\n }\n\n // node_modules/typebox/build/schema/types/maximum.mjs\n function IsMaximum(schema) {\n return guard_exports.HasPropertyKey(schema, \"maximum\") && (guard_exports.IsNumber(schema.maximum) || guard_exports.IsBigInt(schema.maximum));\n }\n\n // node_modules/typebox/build/schema/types/maxContains.mjs\n function IsMaxContains(schema) {\n return guard_exports.HasPropertyKey(schema, \"maxContains\") && guard_exports.IsNumber(schema.maxContains);\n }\n\n // node_modules/typebox/build/schema/types/maxItems.mjs\n function IsMaxItems(schema) {\n return guard_exports.HasPropertyKey(schema, \"maxItems\") && guard_exports.IsNumber(schema.maxItems);\n }\n\n // node_modules/typebox/build/schema/types/maxLength.mjs\n function IsMaxLength4(schema) {\n return guard_exports.HasPropertyKey(schema, \"maxLength\") && guard_exports.IsNumber(schema.maxLength);\n }\n\n // node_modules/typebox/build/schema/types/maxProperties.mjs\n function IsMaxProperties(schema) {\n return guard_exports.HasPropertyKey(schema, \"maxProperties\") && guard_exports.IsNumber(schema.maxProperties);\n }\n\n // node_modules/typebox/build/schema/types/minimum.mjs\n function IsMinimum(schema) {\n return guard_exports.HasPropertyKey(schema, \"minimum\") && (guard_exports.IsNumber(schema.minimum) || guard_exports.IsBigInt(schema.minimum));\n }\n\n // node_modules/typebox/build/schema/types/minContains.mjs\n function IsMinContains(schema) {\n return guard_exports.HasPropertyKey(schema, \"minContains\") && guard_exports.IsNumber(schema.minContains);\n }\n\n // node_modules/typebox/build/schema/types/minItems.mjs\n function IsMinItems(schema) {\n return guard_exports.HasPropertyKey(schema, \"minItems\") && guard_exports.IsNumber(schema.minItems);\n }\n\n // node_modules/typebox/build/schema/types/minLength.mjs\n function IsMinLength4(schema) {\n return guard_exports.HasPropertyKey(schema, \"minLength\") && guard_exports.IsNumber(schema.minLength);\n }\n\n // node_modules/typebox/build/schema/types/minProperties.mjs\n function IsMinProperties(schema) {\n return guard_exports.HasPropertyKey(schema, \"minProperties\") && guard_exports.IsNumber(schema.minProperties);\n }\n\n // node_modules/typebox/build/schema/types/multipleOf.mjs\n function IsMultipleOf2(schema) {\n return guard_exports.HasPropertyKey(schema, \"multipleOf\") && (guard_exports.IsNumber(schema.multipleOf) || guard_exports.IsBigInt(schema.multipleOf));\n }\n\n // node_modules/typebox/build/schema/types/not.mjs\n function IsNot(schema) {\n return guard_exports.HasPropertyKey(schema, \"not\") && IsSchema(schema.not);\n }\n\n // node_modules/typebox/build/schema/types/oneOf.mjs\n function IsOneOf(schema) {\n return guard_exports.HasPropertyKey(schema, \"oneOf\") && guard_exports.IsArray(schema.oneOf) && schema.oneOf.every((value) => IsSchema(value));\n }\n\n // node_modules/typebox/build/schema/types/pattern.mjs\n function IsPattern(schema) {\n return guard_exports.HasPropertyKey(schema, \"pattern\") && (guard_exports.IsString(schema.pattern) || schema.pattern instanceof RegExp);\n }\n\n // node_modules/typebox/build/schema/types/patternProperties.mjs\n function IsPatternProperties(schema) {\n return guard_exports.HasPropertyKey(schema, \"patternProperties\") && guard_exports.IsObject(schema.patternProperties) && Object.values(schema.patternProperties).every((value) => IsSchema(value));\n }\n\n // node_modules/typebox/build/schema/types/prefixItems.mjs\n function IsPrefixItems(schema) {\n return guard_exports.HasPropertyKey(schema, \"prefixItems\") && guard_exports.IsArray(schema.prefixItems) && schema.prefixItems.every((schema2) => IsSchema(schema2));\n }\n\n // node_modules/typebox/build/schema/types/properties.mjs\n function IsProperties(schema) {\n return guard_exports.HasPropertyKey(schema, \"properties\") && guard_exports.IsObject(schema.properties) && Object.values(schema.properties).every((value) => IsSchema(value));\n }\n\n // node_modules/typebox/build/schema/types/propertyNames.mjs\n function IsPropertyNames(schema) {\n return guard_exports.HasPropertyKey(schema, \"propertyNames\") && (guard_exports.IsObject(schema.propertyNames) || IsSchema(schema.propertyNames));\n }\n\n // node_modules/typebox/build/schema/types/recursiveAnchor.mjs\n function IsRecursiveAnchor(schema) {\n return guard_exports.HasPropertyKey(schema, \"$recursiveAnchor\") && guard_exports.IsBoolean(schema.$recursiveAnchor);\n }\n function IsRecursiveAnchorTrue(schema) {\n return IsRecursiveAnchor(schema) && guard_exports.IsEqual(schema.$recursiveAnchor, true);\n }\n\n // node_modules/typebox/build/schema/types/recursiveRef.mjs\n function IsRecursiveRef(schema) {\n return guard_exports.HasPropertyKey(schema, \"$recursiveRef\") && guard_exports.IsString(schema.$recursiveRef);\n }\n\n // node_modules/typebox/build/schema/types/ref.mjs\n function IsRef(schema) {\n return guard_exports.HasPropertyKey(schema, \"$ref\") && guard_exports.IsString(schema.$ref);\n }\n\n // node_modules/typebox/build/schema/types/required.mjs\n function IsRequired(schema) {\n return guard_exports.HasPropertyKey(schema, \"required\") && guard_exports.IsArray(schema.required) && schema.required.every((value) => guard_exports.IsString(value));\n }\n\n // node_modules/typebox/build/schema/types/then.mjs\n function IsThen(schema) {\n return guard_exports.HasPropertyKey(schema, \"then\") && IsSchema(schema.then);\n }\n\n // node_modules/typebox/build/schema/types/type.mjs\n function IsType(schema) {\n return guard_exports.HasPropertyKey(schema, \"type\") && (guard_exports.IsString(schema.type) || guard_exports.IsArray(schema.type) && schema.type.every((value) => guard_exports.IsString(value)));\n }\n\n // node_modules/typebox/build/schema/types/uniqueItems.mjs\n function IsUniqueItems(schema) {\n return guard_exports.HasPropertyKey(schema, \"uniqueItems\") && guard_exports.IsBoolean(schema.uniqueItems);\n }\n\n // node_modules/typebox/build/schema/types/unevaluatedItems.mjs\n function IsUnevaluatedItems(schema) {\n return guard_exports.HasPropertyKey(schema, \"unevaluatedItems\") && IsSchema(schema.unevaluatedItems);\n }\n\n // node_modules/typebox/build/schema/types/unevaluatedProperties.mjs\n function IsUnevaluatedProperties(schema) {\n return guard_exports.HasPropertyKey(schema, \"unevaluatedProperties\") && IsSchema(schema.unevaluatedProperties);\n }\n\n // node_modules/typebox/build/schema/engine/_context.mjs\n function HasUnevaluatedFromObject(value) {\n return IsUnevaluatedItems(value) || IsUnevaluatedProperties(value) || guard_exports.Some(guard_exports.Keys(value), (key) => HasUnevaluatedFromUnknown(value[key]));\n }\n function HasUnevaluatedFromArray(value) {\n return guard_exports.Some(value, (value2) => HasUnevaluatedFromUnknown(value2));\n }\n function HasUnevaluatedFromUnknown(value) {\n return guard_exports.IsArray(value) ? HasUnevaluatedFromArray(value) : guard_exports.IsObject(value) ? HasUnevaluatedFromObject(value) : false;\n }\n function HasUnevaluated(context2, schema) {\n return HasUnevaluatedFromUnknown(schema) || guard_exports.Some(guard_exports.Keys(context2), (key) => HasUnevaluatedFromUnknown(context2[key]));\n }\n var BuildContext = class {\n constructor(hasUnevaluated) {\n this.hasUnevaluated = hasUnevaluated;\n }\n UseUnevaluated() {\n return this.hasUnevaluated;\n }\n // ----------------------------------------------------------------\n // Stack\n // ----------------------------------------------------------------\n Push() {\n return emit_exports.Call(emit_exports.Member(\"context\", \"Push\"), []);\n }\n Pop() {\n return emit_exports.Call(emit_exports.Member(\"context\", \"Pop\"), []);\n }\n // ----------------------------------------------------------------\n // Top\n // ----------------------------------------------------------------\n AddIndex(index3) {\n return emit_exports.Call(emit_exports.Member(\"context\", \"AddIndex\"), [index3]);\n }\n AddKey(key) {\n return emit_exports.Call(emit_exports.Member(\"context\", \"AddKey\"), [key]);\n }\n Merge(results) {\n return emit_exports.Call(emit_exports.Member(\"context\", \"Merge\"), [results]);\n }\n };\n var CheckContext = class {\n constructor() {\n const indices = /* @__PURE__ */ new Set();\n const keys = /* @__PURE__ */ new Set();\n this.stack = [{ indices, keys }];\n }\n // ----------------------------------------------------------------\n // Stack\n // ----------------------------------------------------------------\n Push() {\n const indices = /* @__PURE__ */ new Set();\n const keys = /* @__PURE__ */ new Set();\n this.stack.push({ indices, keys });\n return true;\n }\n Pop() {\n this.stack.pop();\n return true;\n }\n // ----------------------------------------------------------------\n // Top\n // ----------------------------------------------------------------\n AddIndex(index3) {\n this.GetIndices().add(index3);\n return true;\n }\n AddKey(key) {\n this.GetKeys().add(key);\n return true;\n }\n GetIndices() {\n const top = this.stack[this.stack.length - 1];\n return top.indices;\n }\n GetKeys() {\n const top = this.stack[this.stack.length - 1];\n return top.keys;\n }\n Merge(results) {\n for (const context2 of results) {\n context2.GetIndices().forEach((value) => this.GetIndices().add(value));\n context2.GetKeys().forEach((value) => this.GetKeys().add(value));\n }\n return true;\n }\n };\n var ErrorContext = class extends CheckContext {\n constructor() {\n super();\n this.errors = [];\n }\n AtCapacity() {\n return this.errors.length >= settings_exports.Get().maxErrors;\n }\n AddError(error) {\n if (!this.AtCapacity())\n this.errors.push(error);\n return false;\n }\n GetErrors() {\n return this.errors;\n }\n };\n\n // node_modules/typebox/build/schema/engine/_externals.mjs\n var state = {\n identifier: \"External\",\n variables: []\n };\n function CreateVariable(value) {\n const call = `External[${state.variables.length}]`;\n state.variables.push(value);\n return call;\n }\n function ResetExternal() {\n state.variables = [];\n }\n function GetExternal() {\n return { ...state };\n }\n\n // node_modules/typebox/build/schema/engine/_refine.mjs\n function BuildRefine(_stack, _context, schema, value) {\n const refinements = CreateVariable(schema[\"~refine\"].map((refinement) => refinement));\n return emit_exports.Every(refinements, emit_exports.Constant(0), [\"refinement\", \"_\"], emit_exports.Call(emit_exports.Member(\"refinement\", \"check\"), [value]));\n }\n function CheckRefine(_stack, _context, schema, value) {\n return guard_exports.Every(schema[\"~refine\"], 0, (refinement, _) => refinement.check(value));\n }\n function ErrorRefine(_stack, context2, schemaPath, instancePath, schema, value) {\n return guard_exports.EveryAll(schema[\"~refine\"], 0, (refinement, index3) => {\n return refinement.check(value) || context2.AddError({\n keyword: \"~refine\",\n schemaPath,\n instancePath,\n params: { index: index3, message: refinement.error(value) }\n });\n });\n }\n\n // node_modules/typebox/build/schema/engine/_unique.mjs\n var index = 0;\n function Unique() {\n return `var_${index++}`;\n }\n\n // node_modules/typebox/build/schema/engine/additionalItems.mjs\n function IsValid(schema) {\n return IsItems(schema) && guard_exports.IsArray(schema.items);\n }\n function BuildAdditionalItemsStandard(stack, context2, schema, value) {\n const [item, index3] = [Unique(), Unique()];\n const isSchema = BuildSchemaPushStack(stack, context2, schema.additionalItems, item);\n const isLength = emit_exports.IsLessThan(index3, emit_exports.Constant(schema.items.length));\n const addIndex = context2.AddIndex(index3);\n return emit_exports.Every(value, emit_exports.Constant(0), [item, index3], emit_exports.Or(isLength, emit_exports.And(isSchema, addIndex)));\n }\n function BuildAdditionalItemsFast(stack, context2, schema, value) {\n const [item, index3] = [Unique(), Unique()];\n const isSchema = BuildSchemaPushStack(stack, context2, schema.additionalItems, item);\n const isLength = emit_exports.IsLessThan(index3, emit_exports.Constant(schema.items.length));\n return emit_exports.Every(value, emit_exports.Constant(0), [item, index3], emit_exports.Or(isLength, isSchema));\n }\n function BuildAdditionalItems(stack, context2, schema, value) {\n if (!IsValid(schema))\n return emit_exports.Constant(true);\n return context2.UseUnevaluated() ? BuildAdditionalItemsStandard(stack, context2, schema, value) : BuildAdditionalItemsFast(stack, context2, schema, value);\n }\n function CheckAdditionalItems(stack, context2, schema, value) {\n if (!IsValid(schema))\n return true;\n const isAdditionalItems = guard_exports.Every(value, 0, (item, index3) => {\n return guard_exports.IsLessThan(index3, schema.items.length) || CheckSchemaPushStack(stack, context2, schema.additionalItems, item) && context2.AddIndex(index3);\n });\n return isAdditionalItems;\n }\n function ErrorAdditionalItems(stack, context2, schemaPath, instancePath, schema, value) {\n if (!IsValid(schema))\n return true;\n const isAdditionalItems = guard_exports.Every(value, 0, (item, index3) => {\n const nextSchemaPath = `${schemaPath}/additionalItems`;\n const nextInstancePath = `${instancePath}/${index3}`;\n return guard_exports.IsLessThan(index3, schema.items.length) || ErrorSchemaPushStack(stack, context2, nextSchemaPath, nextInstancePath, schema.additionalItems, item) && context2.AddIndex(index3);\n });\n return isAdditionalItems;\n }\n\n // node_modules/typebox/build/schema/engine/_regexp.mjs\n function UnicodeRegExp(pattern) {\n return new RegExp(pattern, \"u\");\n }\n\n // node_modules/typebox/build/schema/engine/additionalProperties.mjs\n function IsAdditionalPropertiesIgnored(context2, additionalProperties) {\n return !context2.UseUnevaluated() && (guard_exports.IsEqual(additionalProperties, true) || guard_exports.IsObject(additionalProperties) && guard_exports.IsEqual(guard_exports.Keys(additionalProperties).length, 0));\n }\n function GetPropertyKeyAsPattern(key) {\n const escaped = key.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return `^${escaped}$`;\n }\n function GetPropertiesPattern(schema) {\n const patterns = [];\n if (IsPatternProperties(schema))\n patterns.push(...guard_exports.Keys(schema.patternProperties));\n if (IsProperties(schema))\n patterns.push(...guard_exports.Keys(schema.properties).map(GetPropertyKeyAsPattern));\n return guard_exports.IsEqual(patterns.length, 0) ? \"(?!)\" : `(${patterns.join(\"|\")})`;\n }\n function CanAdditionalPropertiesFast(_context, schema, _value) {\n return IsRequired(schema) && IsProperties(schema) && !IsPatternProperties(schema) && guard_exports.IsEqual(schema.additionalProperties, false) && guard_exports.IsEqual(guard_exports.Keys(schema.properties).length, schema.required.length);\n }\n function BuildAdditionalPropertiesFast(_context, schema, value) {\n return emit_exports.IsEqual(emit_exports.Member(emit_exports.Call(emit_exports.Member(\"Object\", \"getOwnPropertyNames\"), [value]), \"length\"), emit_exports.Constant(schema.required.length));\n }\n function BuildAdditionalPropertiesStandard(stack, context2, schema, value) {\n const [key, _index] = [Unique(), Unique()];\n const regexp = CreateVariable(UnicodeRegExp(GetPropertiesPattern(schema)));\n const isSchema = BuildSchemaPushStack(stack, context2, schema.additionalProperties, `${value}[${key}]`);\n const isKey = emit_exports.Call(emit_exports.Member(regexp, \"test\"), [key]);\n const addKey = context2.AddKey(key);\n const guarded = context2.UseUnevaluated() ? emit_exports.Or(isKey, emit_exports.And(isSchema, addKey)) : emit_exports.Or(isKey, isSchema);\n const result = emit_exports.Every(emit_exports.Keys(value), emit_exports.Constant(0), [key, _index], guarded);\n return result;\n }\n function BuildAdditionalProperties(stack, context2, schema, value) {\n if (IsAdditionalPropertiesIgnored(context2, schema.additionalProperties))\n return emit_exports.Constant(true);\n return CanAdditionalPropertiesFast(context2, schema, value) ? BuildAdditionalPropertiesFast(context2, schema, value) : BuildAdditionalPropertiesStandard(stack, context2, schema, value);\n }\n function CheckAdditionalProperties(stack, context2, schema, value) {\n const regexp = UnicodeRegExp(GetPropertiesPattern(schema));\n const isAdditionalProperties = guard_exports.Every(guard_exports.Keys(value), 0, (key, _index) => {\n return regexp.test(key) || CheckSchemaPushStack(stack, context2, schema.additionalProperties, value[key]) && context2.AddKey(key);\n });\n return isAdditionalProperties;\n }\n function ErrorAdditionalProperties(stack, context2, schemaPath, instancePath, schema, value) {\n const regexp = UnicodeRegExp(GetPropertiesPattern(schema));\n const additionalProperties = [];\n const isAdditionalProperties = guard_exports.EveryAll(guard_exports.Keys(value), 0, (key, _index) => {\n const nextSchemaPath = `${schemaPath}/additionalProperties`;\n const nextInstancePath = `${instancePath}/${key}`;\n const isAdditionalProperty = regexp.test(key) || ErrorSchemaPushStack(stack, context2, nextSchemaPath, nextInstancePath, schema.additionalProperties, value[key]) && context2.AddKey(key);\n if (!isAdditionalProperty)\n additionalProperties.push(key);\n return isAdditionalProperty;\n });\n return isAdditionalProperties || context2.AddError({\n keyword: \"additionalProperties\",\n schemaPath,\n instancePath,\n params: { additionalProperties }\n });\n }\n\n // node_modules/typebox/build/schema/engine/_reducer.mjs\n function Reducer(stack, context2, schemas, value, check) {\n const results = emit_exports.ConstDeclaration(\"results\", \"[]\");\n const context_n = schemas.map((_schema, index3) => emit_exports.ConstDeclaration(`context_${index3}`, emit_exports.New(\"CheckContext\", [])));\n const condition_n = schemas.map((schema, index3) => emit_exports.ConstDeclaration(`condition_${index3}`, emit_exports.Call(emit_exports.ArrowFunction([\"context\"], BuildSchema(stack, context2, schema, value)), [`context_${index3}`])));\n const checks = schemas.map((_schema, index3) => emit_exports.If(`condition_${index3}`, emit_exports.Call(emit_exports.Member(\"results\", \"push\"), [`context_${index3}`])));\n const returns = emit_exports.Return(emit_exports.And(check, context2.Merge(\"results\")));\n return emit_exports.Call(emit_exports.ArrowFunction([], emit_exports.Statements([results, ...context_n, ...condition_n, ...checks, returns])), []);\n }\n\n // node_modules/typebox/build/schema/engine/allOf.mjs\n function BuildAllOfStandard(stack, context2, schema, value) {\n return Reducer(stack, context2, schema.allOf, value, emit_exports.IsEqual(emit_exports.Member(\"results\", \"length\"), emit_exports.Constant(schema.allOf.length)));\n }\n function BuildAllOfFast(stack, context2, schema, value) {\n return emit_exports.ReduceAnd(schema.allOf.map((schema2) => BuildSchema(stack, context2, schema2, value)));\n }\n function BuildAllOf(stack, context2, schema, value) {\n return context2.UseUnevaluated() ? BuildAllOfStandard(stack, context2, schema, value) : BuildAllOfFast(stack, context2, schema, value);\n }\n function CheckAllOf(stack, context2, schema, value) {\n const results = schema.allOf.reduce((result, schema2) => {\n const nextContext = new CheckContext();\n return CheckSchema(stack, nextContext, schema2, value) ? [...result, nextContext] : result;\n }, []);\n return guard_exports.IsEqual(results.length, schema.allOf.length) && context2.Merge(results);\n }\n function ErrorAllOf(stack, context2, schemaPath, instancePath, schema, value) {\n const failedContexts = [];\n const results = schema.allOf.reduce((result, schema2, index3) => {\n const nextSchemaPath = `${schemaPath}/allOf/${index3}`;\n const nextContext = new ErrorContext();\n const isSchema = ErrorSchema(stack, nextContext, nextSchemaPath, instancePath, schema2, value);\n if (!isSchema)\n failedContexts.push(nextContext);\n return isSchema ? [...result, nextContext] : result;\n }, []);\n const isAllOf = guard_exports.IsEqual(results.length, schema.allOf.length) && context2.Merge(results);\n if (!isAllOf)\n failedContexts.forEach((failed) => failed.GetErrors().forEach((error) => context2.AddError(error)));\n return isAllOf;\n }\n\n // node_modules/typebox/build/schema/engine/anyOf.mjs\n function BuildAnyOfStandard(stack, context2, schema, value) {\n return Reducer(stack, context2, schema.anyOf, value, emit_exports.IsGreaterThan(emit_exports.Member(\"results\", \"length\"), emit_exports.Constant(0)));\n }\n function BuildAnyOfFast(stack, context2, schema, value) {\n return emit_exports.ReduceOr(schema.anyOf.map((schema2) => BuildSchema(stack, context2, schema2, value)));\n }\n function BuildAnyOf(stack, context2, schema, value) {\n return context2.UseUnevaluated() ? BuildAnyOfStandard(stack, context2, schema, value) : BuildAnyOfFast(stack, context2, schema, value);\n }\n function CheckAnyOf(stack, context2, schema, value) {\n const results = schema.anyOf.reduce((result, schema2) => {\n const nextContext = new CheckContext();\n return CheckSchema(stack, nextContext, schema2, value) ? [...result, nextContext] : result;\n }, []);\n return guard_exports.IsGreaterThan(results.length, 0) && context2.Merge(results);\n }\n function ErrorAnyOf(stack, context2, schemaPath, instancePath, schema, value) {\n const failedContexts = [];\n const results = schema.anyOf.reduce((result, schema2, index3) => {\n const nextContext = new ErrorContext();\n const nextSchemaPath = `${schemaPath}/anyOf/${index3}`;\n const isSchema = ErrorSchema(stack, nextContext, nextSchemaPath, instancePath, schema2, value);\n if (!isSchema)\n failedContexts.push(nextContext);\n return isSchema ? [...result, nextContext] : result;\n }, []);\n const isAnyOf = guard_exports.IsGreaterThan(results.length, 0) && context2.Merge(results);\n if (!isAnyOf)\n failedContexts.forEach((failed) => failed.GetErrors().forEach((error) => context2.AddError(error)));\n return isAnyOf || context2.AddError({\n keyword: \"anyOf\",\n schemaPath,\n instancePath,\n params: {}\n });\n }\n\n // node_modules/typebox/build/schema/engine/boolean.mjs\n function BuildSchemaBoolean(_stack, _context, schema, _value) {\n return schema ? emit_exports.Constant(true) : emit_exports.Constant(false);\n }\n function CheckSchemaBoolean(_stack, _context, schema, _value) {\n return schema;\n }\n function ErrorSchemaBoolean(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckSchemaBoolean(stack, context2, schema, value) || context2.AddError({\n keyword: \"boolean\",\n schemaPath,\n instancePath,\n params: {}\n });\n }\n\n // node_modules/typebox/build/schema/engine/const.mjs\n function BuildConst(_stack, _context, schema, value) {\n return guard_exports.IsValueLike(schema.const) ? emit_exports.IsEqual(value, emit_exports.Constant(schema.const)) : emit_exports.IsDeepEqual(value, CreateVariable(schema.const));\n }\n function CheckConst(_stack, _context, schema, value) {\n return guard_exports.IsValueLike(schema.const) ? guard_exports.IsEqual(value, schema.const) : guard_exports.IsDeepEqual(value, schema.const);\n }\n function ErrorConst(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckConst(stack, context2, schema, value) || context2.AddError({\n keyword: \"const\",\n schemaPath,\n instancePath,\n params: { allowedValue: schema.const }\n });\n }\n\n // node_modules/typebox/build/schema/engine/contains.mjs\n function IsValid2(schema) {\n return !(IsMinContains(schema) && guard_exports.IsEqual(schema.minContains, 0));\n }\n function BuildContainsStandard(stack, context2, schema, value) {\n const [item, index3] = [Unique(), Unique()];\n const isLength = emit_exports.Not(emit_exports.IsEqual(emit_exports.Member(value, \"length\"), emit_exports.Constant(0)));\n const isSome = emit_exports.SomeAll(value, [item, index3], emit_exports.And(BuildSchema(stack, context2, schema.contains, item), context2.AddIndex(index3)));\n return emit_exports.And(isLength, isSome);\n }\n function BuildContainsFast(stack, context2, schema, value) {\n const [item] = [Unique()];\n const isLength = emit_exports.Not(emit_exports.IsEqual(emit_exports.Member(value, \"length\"), emit_exports.Constant(0)));\n const isSome = emit_exports.Some(value, [item, \"_\"], BuildSchema(stack, context2, schema.contains, item));\n return emit_exports.And(isLength, isSome);\n }\n function BuildContains(stack, context2, schema, value) {\n if (!IsValid2(schema))\n return emit_exports.Constant(true);\n return context2.UseUnevaluated() ? BuildContainsStandard(stack, context2, schema, value) : BuildContainsFast(stack, context2, schema, value);\n }\n function CheckContains(stack, context2, schema, value) {\n if (!IsValid2(schema))\n return true;\n return !guard_exports.IsEqual(value.length, 0) && guard_exports.SomeAll(value, (item, index3) => {\n return CheckSchema(stack, context2, schema.contains, item) && context2.AddIndex(index3);\n });\n }\n function ErrorContains(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckContains(stack, context2, schema, value) || context2.AddError({\n keyword: \"contains\",\n schemaPath,\n instancePath,\n params: { minContains: 1 }\n });\n }\n\n // node_modules/typebox/build/schema/engine/dependencies.mjs\n function BuildDependencies(stack, context2, schema, value) {\n const isLength = emit_exports.IsEqual(emit_exports.Member(emit_exports.Keys(value), \"length\"), emit_exports.Constant(0));\n const isEveryDependency = emit_exports.ReduceAnd(guard_exports.Entries(schema.dependencies).map(([key, schema2]) => {\n const notKey = emit_exports.Not(emit_exports.HasPropertyKey(value, emit_exports.Constant(key)));\n const isSchema = BuildSchema(stack, context2, schema2, value);\n const isEveryKey = (schema3) => emit_exports.ReduceAnd(schema3.map((key2) => emit_exports.HasPropertyKey(value, emit_exports.Constant(key2))));\n return emit_exports.Or(notKey, guard_exports.IsArray(schema2) ? isEveryKey(schema2) : isSchema);\n }));\n return emit_exports.Or(isLength, isEveryDependency);\n }\n function CheckDependencies(stack, context2, schema, value) {\n const isLength = guard_exports.IsEqual(guard_exports.Keys(value).length, 0);\n const isEvery = guard_exports.Every(guard_exports.Entries(schema.dependencies), 0, ([key, schema2]) => {\n return !guard_exports.HasPropertyKey(value, key) || (guard_exports.IsArray(schema2) ? schema2.every((key2) => guard_exports.HasPropertyKey(value, key2)) : CheckSchema(stack, context2, schema2, value));\n });\n return isLength || isEvery;\n }\n function ErrorDependencies(stack, context2, schemaPath, instancePath, schema, value) {\n const isLength = guard_exports.IsEqual(guard_exports.Keys(value).length, 0);\n const isEvery = guard_exports.EveryAll(guard_exports.Entries(schema.dependencies), 0, ([key, schema2]) => {\n const nextSchemaPath = `${schemaPath}/dependencies/${key}`;\n return !guard_exports.HasPropertyKey(value, key) || (guard_exports.IsArray(schema2) ? schema2.every((dependency) => guard_exports.HasPropertyKey(value, dependency) || context2.AddError({\n keyword: \"dependencies\",\n schemaPath,\n instancePath,\n params: { property: key, dependencies: schema2 }\n })) : ErrorSchema(stack, context2, nextSchemaPath, instancePath, schema2, value));\n });\n return isLength || isEvery;\n }\n\n // node_modules/typebox/build/schema/engine/dependentRequired.mjs\n function BuildDependentRequired(_stack, _context, schema, value) {\n const isLength = emit_exports.IsEqual(emit_exports.Member(emit_exports.Keys(value), \"length\"), emit_exports.Constant(0));\n const isEvery = emit_exports.ReduceAnd(guard_exports.Entries(schema.dependentRequired).map(([key, keys]) => {\n const notKey = emit_exports.Not(emit_exports.HasPropertyKey(value, emit_exports.Constant(key)));\n const everyKey = emit_exports.ReduceAnd(keys.map((key2) => emit_exports.HasPropertyKey(value, emit_exports.Constant(key2))));\n return emit_exports.Or(notKey, everyKey);\n }));\n return emit_exports.Or(isLength, isEvery);\n }\n function CheckDependentRequired(_stack, _context, schema, value) {\n const isLength = guard_exports.IsEqual(guard_exports.Keys(value).length, 0);\n const isEvery = guard_exports.Every(guard_exports.Entries(schema.dependentRequired), 0, ([key, keys]) => {\n return !guard_exports.HasPropertyKey(value, key) || keys.every((key2) => guard_exports.HasPropertyKey(value, key2));\n });\n return isLength || isEvery;\n }\n function ErrorDependentRequired(_stack, context2, schemaPath, instancePath, schema, value) {\n const isLength = guard_exports.IsEqual(guard_exports.Keys(value).length, 0);\n const isEveryEntry = guard_exports.EveryAll(guard_exports.Entries(schema.dependentRequired), 0, ([key, keys]) => {\n return !guard_exports.HasPropertyKey(value, key) || guard_exports.EveryAll(keys, 0, (dependency) => guard_exports.HasPropertyKey(value, dependency) || context2.AddError({\n keyword: \"dependentRequired\",\n schemaPath,\n instancePath,\n params: { property: key, dependencies: keys }\n }));\n });\n return isLength || isEveryEntry;\n }\n\n // node_modules/typebox/build/schema/engine/dependentSchemas.mjs\n function BuildDependentSchemas(stack, context2, schema, value) {\n const isLength = emit_exports.IsEqual(emit_exports.Member(emit_exports.Keys(value), \"length\"), emit_exports.Constant(0));\n const isEvery = emit_exports.ReduceAnd(guard_exports.Entries(schema.dependentSchemas).map(([key, schema2]) => {\n const notKey = emit_exports.Not(emit_exports.HasPropertyKey(value, emit_exports.Constant(key)));\n const isSchema = BuildSchema(stack, context2, schema2, value);\n return emit_exports.Or(notKey, isSchema);\n }));\n return emit_exports.Or(isLength, isEvery);\n }\n function CheckDependentSchemas(stack, context2, schema, value) {\n const isLength = guard_exports.IsEqual(guard_exports.Keys(value).length, 0);\n const isEvery = guard_exports.Every(guard_exports.Entries(schema.dependentSchemas), 0, ([key, schema2]) => {\n return !guard_exports.HasPropertyKey(value, key) || CheckSchema(stack, context2, schema2, value);\n });\n return isLength || isEvery;\n }\n function ErrorDependentSchemas(stack, context2, schemaPath, instancePath, schema, value) {\n const isLength = guard_exports.IsEqual(guard_exports.Keys(value).length, 0);\n const isEvery = guard_exports.EveryAll(guard_exports.Entries(schema.dependentSchemas), 0, ([key, schema2]) => {\n const nextSchemaPath = `${schemaPath}/dependentSchemas/${key}`;\n return !guard_exports.HasPropertyKey(value, key) || ErrorSchema(stack, context2, nextSchemaPath, instancePath, schema2, value);\n });\n return isLength || isEvery;\n }\n\n // node_modules/typebox/build/schema/engine/dynamicRef.mjs\n function BuildDynamicRef(stack, context2, schema, value) {\n const target = stack.DynamicRef(schema) ?? false;\n return CreateFunction(stack, context2, target, value);\n }\n function CheckDynamicRef(stack, context2, schema, value) {\n const target = stack.DynamicRef(schema) ?? false;\n return IsSchema(target) && CheckSchema(stack, context2, target, value);\n }\n function ErrorDynamicRef(stack, context2, _schemaPath, instancePath, schema, value) {\n const target = stack.DynamicRef(schema) ?? false;\n return IsSchema(target) && ErrorSchema(stack, context2, \"#\", instancePath, target, value);\n }\n\n // node_modules/typebox/build/schema/engine/enum.mjs\n function BuildEnum(_stack, _context, schema, value) {\n return emit_exports.ReduceOr(schema.enum.map((option) => {\n if (guard_exports.IsValueLike(option))\n return emit_exports.IsEqual(value, emit_exports.Constant(option));\n const variable = CreateVariable(option);\n return emit_exports.IsDeepEqual(value, variable);\n }));\n }\n function CheckEnum(_stack, _context, schema, value) {\n return guard_exports.Some(schema.enum, (option) => guard_exports.IsValueLike(option) ? guard_exports.IsEqual(value, option) : guard_exports.IsDeepEqual(value, option));\n }\n function ErrorEnum(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckEnum(stack, context2, schema, value) || context2.AddError({\n keyword: \"enum\",\n schemaPath,\n instancePath,\n params: { allowedValues: schema.enum }\n });\n }\n\n // node_modules/typebox/build/schema/engine/exclusiveMaximum.mjs\n function BuildExclusiveMaximum(_stack, _context, schema, value) {\n return emit_exports.IsLessThan(value, emit_exports.Constant(schema.exclusiveMaximum));\n }\n function CheckExclusiveMaximum(_stack, _context, schema, value) {\n return guard_exports.IsLessThan(value, schema.exclusiveMaximum);\n }\n function ErrorExclusiveMaximum(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckExclusiveMaximum(stack, context2, schema, value) || context2.AddError({\n keyword: \"exclusiveMaximum\",\n schemaPath,\n instancePath,\n params: { comparison: \"<\", limit: schema.exclusiveMaximum }\n });\n }\n\n // node_modules/typebox/build/schema/engine/exclusiveMinimum.mjs\n function BuildExclusiveMinimum(_stack, _context, schema, value) {\n return emit_exports.IsGreaterThan(value, emit_exports.Constant(schema.exclusiveMinimum));\n }\n function CheckExclusiveMinimum(_stack, _context, schema, value) {\n return guard_exports.IsGreaterThan(value, schema.exclusiveMinimum);\n }\n function ErrorExclusiveMinimum(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckExclusiveMinimum(stack, context2, schema, value) || context2.AddError({\n keyword: \"exclusiveMinimum\",\n schemaPath,\n instancePath,\n params: { comparison: \">\", limit: schema.exclusiveMinimum }\n });\n }\n\n // node_modules/typebox/build/format/format.mjs\n var format_exports = {};\n __export(format_exports, {\n Clear: () => Clear,\n Entries: () => Entries3,\n Get: () => Get2,\n Has: () => Has,\n IsDate: () => IsDate2,\n IsDateTime: () => IsDateTime,\n IsDuration: () => IsDuration,\n IsEmail: () => IsEmail,\n IsHostname: () => IsHostname2,\n IsIPv4: () => IsIPv4,\n IsIPv6: () => IsIPv6,\n IsIdnEmail: () => IsIdnEmail,\n IsIdnHostname: () => IsIdnHostname2,\n IsIri: () => IsIri,\n IsIriReference: () => IsIriReference,\n IsJsonPointer: () => IsJsonPointer,\n IsJsonPointerUriFragment: () => IsJsonPointerUriFragment,\n IsRegex: () => IsRegex,\n IsRelativeJsonPointer: () => IsRelativeJsonPointer,\n IsTime: () => IsTime,\n IsUri: () => IsUri,\n IsUriReference: () => IsUriReference,\n IsUriTemplate: () => IsUriTemplate,\n IsUrl: () => IsUrl,\n IsUuid: () => IsUuid,\n Reset: () => Reset2,\n Set: () => Set3,\n Test: () => Test\n });\n\n // node_modules/typebox/build/format/date.mjs\n var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n var DATE = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/;\n function IsLeapYear(year) {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n }\n function IsDate2(value) {\n const matches = DATE.exec(value);\n if (!matches)\n return false;\n const year = +matches[1];\n const month = +matches[2];\n const day = +matches[3];\n return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && IsLeapYear(year) ? 29 : DAYS[month]);\n }\n\n // node_modules/typebox/build/format/time.mjs\n var TIME = /^(\\d\\d):(\\d\\d):(\\d\\d)(?:\\.\\d+)?(?:([Zz])|([+-])(\\d\\d):(\\d\\d))?$/;\n function IsTime(value, strictTimeZone = true) {\n const matches = TIME.exec(value);\n if (!matches)\n return false;\n if (strictTimeZone && !matches[4] && !matches[5])\n return false;\n const hr = +matches[1];\n const min = +matches[2];\n const sec = +matches[3];\n if (hr > 23 || min > 59 || sec > 60)\n return false;\n if (matches[5]) {\n const tzH2 = +matches[6];\n const tzM2 = +matches[7];\n if (tzH2 > 23 || tzM2 > 59)\n return false;\n }\n if (sec < 60)\n return true;\n const tzSign = matches[5] === \"-\" ? -1 : 1;\n const tzH = +(matches[6] || 0);\n const tzM = +(matches[7] || 0);\n const totalUtcMin = hr * 60 + min - tzSign * (tzH * 60 + tzM);\n return (totalUtcMin % 1440 + 1440) % 1440 === 1439;\n }\n\n // node_modules/typebox/build/format/date_time.mjs\n function IsDateTime(value) {\n const dateTime = value.split(/T/i);\n return dateTime.length === 2 && IsDate2(dateTime[0]) && IsTime(dateTime[1]);\n }\n\n // node_modules/typebox/build/format/duration.mjs\n var Duration = /^P((\\d+Y(\\d+M(\\d+D)?)?|\\d+M(\\d+D)?|\\d+D)(T(\\d+H(\\d+M(\\d+S)?)?|\\d+M(\\d+S)?|\\d+S))?|T(\\d+H(\\d+M(\\d+S)?)?|\\d+M(\\d+S)?|\\d+S)|\\d+W)$/;\n function IsDuration(value) {\n return Duration.test(value);\n }\n\n // node_modules/typebox/build/format/email.mjs\n var Email = /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[^\"\\\\]|\\\\[\\x20-\\x7e])*\")@(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\\[(?:IPv6:[a-f0-9:]+|(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})\\])$/i;\n function IsEmail(value) {\n return Email.test(value);\n }\n\n // node_modules/typebox/build/format/idna/pattern/pattern.mjs\n var RE_RULE_HYPHEN_PLACEMENT = /^(?!-).*(?<!-)$/;\n var RE_RULE_NOT_RESERVED_ACE = /^(?!..--)/;\n var RE_ASCII_LDH = /^[a-zA-Z0-9-]*$/;\n var RE_NON_ASCII = /[^\\p{ASCII}]/u;\n var RE_ASCII_DIGIT = /[0-9]/;\n var RE_ARABIC_INDIC_DIGIT = /[\\u{0660}-\\u{0669}]/u;\n var RE_EXT_ARABIC_INDIC_DIGIT = /[\\u{06f0}-\\u{06f9}]/u;\n var RE_COMMON_SEPARATOR = /[\\u{002e}\\u{002c}\\u{003a}\\u{002f}]/u;\n var RE_EUROPEAN_SEPARATOR = /[\\u{002d}\\u{002b}]/u;\n var RE_MARK_NONSPACING = /\\p{Mn}/u;\n var RE_MARK_SPACING_COMBINING = /\\p{Mc}/u;\n var RE_COMBINING_MARK = /[\\p{Mn}\\p{Mc}\\p{Me}]/u;\n var RE_LETTER = /\\p{L}/u;\n var RE_NUMBER_DECIMAL = /\\p{Nd}/u;\n var RE_SCRIPT_GREEK = /\\p{Script=Greek}/u;\n var RE_SCRIPT_HEBREW = /\\p{Script=Hebrew}/u;\n var RE_SCRIPT_JAPANESE = /[\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Han}]/u;\n var RE_SCRIPT_ARABIC_LETTER = /[\\p{Script=Arabic}\\p{Script=Syriac}\\p{Script=Thaana}\\p{Script=Mandaic}]/u;\n var RE_VIRAMA = /[\\u{094d}\\u{09cd}\\u{0a4d}\\u{0acd}\\u{0b4d}\\u{0bcd}\\u{0c4d}\\u{0ccd}\\u{0d3b}\\u{0d3c}\\u{0d4d}\\u{0dca}\\u{1b44}\\u{1baa}\\u{1bab}\\u{a9c0}\\u{11046}\\u{1107f}\\u{110b9}\\u{11133}\\u{11134}\\u{111c0}\\u{11235}\\u{1134d}\\u{11442}\\u{114c2}\\u{115bf}\\u{1163f}\\u{116b6}\\u{11c3f}\\u{11d44}\\u{11d45}]/u;\n var RE_RFC5892_DISALLOWED = /[\\u{0640}\\u{07fa}\\u{302e}\\u{302f}\\u{3031}\\u{3032}\\u{3033}\\u{3034}\\u{3035}\\u{303b}]/u;\n var RE_CONTEXTO_EXCEPTIONS = /[\\u{00b7}\\u{0375}\\u{05f3}\\u{05f4}\\u{200c}\\u{200d}\\u{30fb}]/u;\n var RE_PVALID_EXCEPTIONS = /[\\u{00df}\\u{03c2}\\u{06fd}\\u{06fe}\\u{0f0b}\\u{3007}]/u;\n var RE_EUROPEAN_NUMBER = new RegExp([\n RE_ASCII_DIGIT,\n RE_EXT_ARABIC_INDIC_DIGIT\n ].map((regexp) => regexp.source).join(\"|\"), \"u\");\n var RE_PERMITTED_CATEGORY = new RegExp([\n RE_LETTER,\n RE_EUROPEAN_SEPARATOR,\n RE_COMMON_SEPARATOR,\n RE_NUMBER_DECIMAL,\n RE_MARK_NONSPACING,\n RE_MARK_SPACING_COMBINING,\n RE_CONTEXTO_EXCEPTIONS,\n RE_PVALID_EXCEPTIONS\n ].map((regexp) => regexp.source).join(\"|\"), \"u\");\n\n // node_modules/typebox/build/format/idna/label/ascii.mjs\n function IsAsciiLabel(value) {\n return RE_RULE_HYPHEN_PLACEMENT.test(value) && RE_RULE_NOT_RESERVED_ACE.test(value) && RE_ASCII_LDH.test(value);\n }\n\n // node_modules/typebox/build/format/idna/format/puny.mjs\n var PUNYCODE_BASE = 36;\n var PUNYCODE_TMIN = 1;\n var PUNYCODE_TMAX = 26;\n var PUNYCODE_SKEW = 38;\n var PUNYCODE_DAMP = 700;\n var PUNYCODE_INITIAL_BIAS = 72;\n var PUNYCODE_INITIAL_N = 128;\n function ThrowDontCare() {\n throw null;\n }\n function IsAcePrefixed(value) {\n return value.toLowerCase().startsWith(\"xn--\");\n }\n function Adapt(delta, numPoints, firstTime) {\n delta = firstTime ? Math.floor(delta / PUNYCODE_DAMP) : delta >> 1;\n delta += Math.floor(delta / numPoints);\n let k = 0;\n while (delta > (PUNYCODE_BASE - PUNYCODE_TMIN) * PUNYCODE_TMAX >> 1) {\n delta = Math.floor(delta / (PUNYCODE_BASE - PUNYCODE_TMIN));\n k += PUNYCODE_BASE;\n }\n return k + Math.floor((PUNYCODE_BASE - PUNYCODE_TMIN + 1) * delta / (delta + PUNYCODE_SKEW));\n }\n function Decode(value) {\n const output = [];\n let n = PUNYCODE_INITIAL_N;\n let i = 0;\n let bias = PUNYCODE_INITIAL_BIAS;\n const delimIdx = value.lastIndexOf(\"-\");\n if (delimIdx > 0) {\n for (let j = 0; j < delimIdx; j++) {\n const cp = value.charCodeAt(j);\n if (cp >= 128)\n ThrowDontCare();\n output.push(cp);\n }\n }\n let inIdx = delimIdx < 0 ? 0 : delimIdx + 1;\n while (inIdx < value.length) {\n const oldi = i;\n let w = 1;\n let k = PUNYCODE_BASE;\n while (true) {\n if (inIdx >= value.length)\n ThrowDontCare();\n const ch = value.charCodeAt(inIdx++);\n let digit;\n if (ch >= 97 && ch <= 122)\n digit = ch - 97;\n else if (ch >= 48 && ch <= 57)\n digit = ch - 48 + 26;\n else\n ThrowDontCare();\n i += digit * w;\n const t = k <= bias ? PUNYCODE_TMIN : k >= bias + PUNYCODE_TMAX ? PUNYCODE_TMAX : k - bias;\n if (digit < t)\n break;\n w *= PUNYCODE_BASE - t;\n k += PUNYCODE_BASE;\n }\n const outLen = output.length + 1;\n bias = Adapt(i - oldi, outLen, oldi === 0);\n n += Math.floor(i / outLen);\n i %= outLen;\n output.splice(i, 0, n);\n i++;\n }\n return String.fromCodePoint(...output);\n }\n function DigitToChar(digit) {\n return digit < 26 ? String.fromCharCode(digit + 97) : String.fromCharCode(digit - 26 + 48);\n }\n var RE_REPLACE_NON_ASCII = new RegExp(RE_NON_ASCII.source, \"gu\");\n function Encode(input) {\n const basic = input.replace(RE_REPLACE_NON_ASCII, \"\");\n const basicLength = basic.length;\n const result = basicLength > 0 ? [basic, \"-\"] : [];\n const codePoints = Array.from(input, (char) => char.codePointAt(0));\n let n = PUNYCODE_INITIAL_N;\n let delta = 0;\n let bias = PUNYCODE_INITIAL_BIAS;\n let handledCPCount = basicLength;\n while (handledCPCount < codePoints.length) {\n let m = Infinity;\n for (const cp of codePoints) {\n if (cp >= n && cp < m)\n m = cp;\n }\n delta += (m - n) * (handledCPCount + 1);\n n = m;\n for (const cp of codePoints) {\n if (cp < n)\n delta++;\n if (cp === n) {\n let q = delta;\n for (let k = PUNYCODE_BASE; ; k += PUNYCODE_BASE) {\n const t = k <= bias ? PUNYCODE_TMIN : k >= bias + PUNYCODE_TMAX ? PUNYCODE_TMAX : k - bias;\n if (q < t)\n break;\n const digit = t + (q - t) % (PUNYCODE_BASE - t);\n result.push(DigitToChar(digit));\n q = Math.floor((q - t) / (PUNYCODE_BASE - t));\n }\n result.push(DigitToChar(q));\n bias = Adapt(delta, handledCPCount + 1, handledCPCount === basicLength);\n delta = 0;\n handledCPCount++;\n }\n }\n delta++;\n n++;\n }\n return result.join(\"\");\n }\n\n // node_modules/typebox/build/format/idna/format/bidi.mjs\n var RE_RTL_ALLOWED = /^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/;\n var RE_LTR_ALLOWED = /^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/;\n var RE_RTL_CLASSES = /^(?:R|AL|AN)$/;\n function HasBidiChars(value) {\n if (IsAcePrefixed(value)) {\n try {\n return HasRightToLeftCharacters(Decode(value.slice(4).toLowerCase()));\n } catch {\n return false;\n }\n }\n return HasRightToLeftCharacters(value);\n }\n function GetBidiClass(codePoint) {\n const char = String.fromCodePoint(codePoint);\n return RE_EUROPEAN_NUMBER.test(char) ? \"EN\" : RE_ARABIC_INDIC_DIGIT.test(char) ? \"AN\" : (\n // Pattern.RE_EUROPEAN_SEPARATOR.test(char) ? 'ES' : // (no-spec-coverage)\n // Pattern.RE_COMMON_SEPARATOR.test(char) ? 'CS' : // (no-spec-coverage)\n RE_MARK_NONSPACING.test(char) ? \"NSM\" : RE_SCRIPT_HEBREW.test(char) ? \"R\" : RE_SCRIPT_ARABIC_LETTER.test(char) ? \"AL\" : RE_LETTER.test(char) ? \"L\" : \"ON\"\n );\n }\n function HasRightToLeftCharacters(value) {\n for (const ch of value)\n if (RE_RTL_CLASSES.test(GetBidiClass(ch.codePointAt(0))))\n return true;\n return false;\n }\n function SatisfiesBidiRule(value) {\n let isRtl = false;\n let allowed = RE_LTR_ALLOWED;\n let sawEN = false;\n let sawAN = false;\n let isFirst = true;\n for (const ch of value) {\n const bidiClass = GetBidiClass(ch.codePointAt(0));\n if (isFirst) {\n if (bidiClass !== \"L\" && bidiClass !== \"R\" && bidiClass !== \"AL\")\n return false;\n isRtl = bidiClass === \"R\" || bidiClass === \"AL\";\n allowed = isRtl ? RE_RTL_ALLOWED : RE_LTR_ALLOWED;\n isFirst = false;\n }\n if (!allowed.test(bidiClass))\n return false;\n if (bidiClass === \"EN\")\n sawEN = true;\n else if (bidiClass === \"AN\")\n sawAN = true;\n }\n if (isRtl && sawEN && sawAN)\n return false;\n return true;\n }\n\n // node_modules/typebox/build/format/idna/label/unicode.mjs\n function ExceedsMaxALabelLength(value) {\n return RE_NON_ASCII.test(value) && Encode(value).length + 4 > 63;\n }\n function HasInvalidHyphens(chars) {\n if (chars[0] === \"-\" || chars[chars.length - 1] === \"-\")\n return true;\n return chars.slice(2).join(\"\").startsWith(\"--\");\n }\n function IsUnicodeLabel(value) {\n if (ExceedsMaxALabelLength(value))\n return false;\n if (HasRightToLeftCharacters(value) && !SatisfiesBidiRule(value))\n return false;\n const chars = [...value];\n const codePoints = chars.map((c) => c.codePointAt(0));\n const length = codePoints.length;\n if (HasInvalidHyphens(chars))\n return false;\n if (RE_COMBINING_MARK.test(chars[0]))\n return false;\n let hasJapanese = false;\n for (let i = 0; i < length; i++) {\n const codePoint = codePoints[i];\n const char = chars[i];\n if (RE_RFC5892_DISALLOWED.test(char))\n return false;\n if (!RE_PERMITTED_CATEGORY.test(char))\n return false;\n if (RE_SCRIPT_JAPANESE.test(char))\n hasJapanese = true;\n const prev = codePoints[i - 1], next = codePoints[i + 1];\n switch (codePoint) {\n case 183:\n if (prev !== 108 || next !== 108)\n return false;\n break;\n // MIDDLE DOT (Catalan)\n case 885:\n if (!next || !RE_SCRIPT_GREEK.test(chars[i + 1]))\n return false;\n break;\n // Greek KERAIA\n case 1523:\n case 1524:\n if (!prev || !RE_SCRIPT_HEBREW.test(chars[i - 1]))\n return false;\n break;\n // Hebrew GERESH\n case 8204:\n if (!prev || prev < 128 && !RE_VIRAMA.test(chars[i - 1]))\n return false;\n break;\n case 8205:\n if (!prev || !RE_VIRAMA.test(chars[i - 1]))\n return false;\n break;\n case 12539:\n break;\n }\n }\n if (value.includes(\"\\u30FB\") && !hasJapanese)\n return false;\n return true;\n }\n\n // node_modules/typebox/build/format/idna/label/puny.mjs\n function IsPunyLabel(value) {\n if (!IsAcePrefixed(value))\n return false;\n try {\n const body = value.slice(4).toLowerCase();\n if (body.lastIndexOf(\"-\") === 0)\n return false;\n const decoded = Decode(body);\n if (!RE_NON_ASCII.test(decoded))\n return false;\n return IsUnicodeLabel(decoded);\n } catch {\n return false;\n }\n }\n\n // node_modules/typebox/build/format/idna/hostname.mjs\n function IsValidLabelLength(value) {\n return value.length > 0 && value.length <= 63;\n }\n function IsLabel(value) {\n return IsValidLabelLength(value) && (IsPunyLabel(value) || IsAsciiLabel(value));\n }\n function IsHostname(value) {\n if (value.length === 0 || value.length > 253)\n return false;\n if (value.charCodeAt(value.length - 1) === 46)\n return false;\n return value.split(\".\").every((label) => IsLabel(label));\n }\n\n // node_modules/typebox/build/format/idna/idn-hostname.mjs\n function IsValidLabelLength2(value) {\n return value.length > 0 && value.length <= 63;\n }\n function IsLabel2(value) {\n return IsValidLabelLength2(value) && (IsPunyLabel(value) || IsUnicodeLabel(value));\n }\n function NormalizeHostname(value) {\n return value.replace(/[\\uff01-\\uff5e]/g, (char) => String.fromCharCode(char.charCodeAt(0) - 65248)).normalize(\"NFC\").replace(/[\\u00ad\\u034f\\u180b-\\u180d\\u200b\\ufe00-\\ufe0f\\u{e0100}-\\u{e01ef}]/gu, \"\").replace(/[\\u002E\\u3002\\uFF0E\\uFF61]/g, \".\");\n }\n function IsIdnHostname(value) {\n if (value.length === 0 || value.includes(\" \"))\n return false;\n const normalized = NormalizeHostname(value);\n if (normalized.length > 253)\n return false;\n const labels = normalized.split(\".\");\n const hasBidiChars = labels.some((label) => HasBidiChars(label));\n return labels.every((label) => IsLabel2(label) && (!hasBidiChars || SatisfiesBidiRule(label)));\n }\n\n // node_modules/typebox/build/format/hostname.mjs\n function IsHostname2(value) {\n return IsHostname(value);\n }\n\n // node_modules/typebox/build/format/idn_email.mjs\n var IdnEmail = /^(?:[A-Za-z0-9!#$%&'*+\\/=?^_`{|}~\\u{0080}-\\u{10FFFF}-]+(?:\\.[A-Za-z0-9!#$%&'*+\\/=?^_`{|}~\\u{0080}-\\u{10FFFF}-]+)*|\"(?:[^\"\\\\]|\\\\.)*\")@[\\p{L}\\p{N}](?:[\\p{L}\\p{N}-]{0,62})(?<!-)(?:\\.[\\p{L}\\p{N}](?:[\\p{L}\\p{N}-]{0,62})(?<!-))*$/iu;\n function IsIdnEmail(value) {\n return IdnEmail.test(value.normalize(\"NFC\"));\n }\n\n // node_modules/typebox/build/format/idn_hostname.mjs\n function IsIdnHostname2(value) {\n return IsIdnHostname(value);\n }\n\n // node_modules/typebox/build/format/ipv4.mjs\n var IPv4 = /^(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)$/;\n function IsIPv4(value) {\n return IPv4.test(value);\n }\n\n // node_modules/typebox/build/format/ipv6.mjs\n var IPv6 = /^(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)$/i;\n function IsIPv6(value) {\n return IPv6.test(value);\n }\n\n // node_modules/typebox/build/format/iri_reference.mjs\n var InvalidIriChars = /[\\x00-\\x20\\x7F\\\\]|%(?![0-9a-fA-F]{2})/;\n var MalformedScheme = /^[a-zA-Z][a-zA-Z0-9+\\-.]*\\/\\//;\n function IsIriReference(value) {\n return !InvalidIriChars.test(value) && !MalformedScheme.test(value) && URL.canParse(value, \"http://example.com\");\n }\n\n // node_modules/typebox/build/format/iri.mjs\n var IpvFutureMatchMaxLength = 2048;\n var IpvFutureMatch = /\\[[vV][0-9a-fA-F]+\\.[^\\]]+\\]/;\n var InvalidIriChars2 = /[\\x00-\\x20<>\\^`{|}\\\\]/;\n var InvalidPercentEncoding = /%(?![0-9a-fA-F]{2})/;\n function NarrowIpvFuture(value) {\n return value.length < IpvFutureMatchMaxLength ? value.replace(IpvFutureMatch, \"[::1]\") : value;\n }\n function IsIri(value) {\n if (InvalidIriChars2.test(value))\n return false;\n if (InvalidPercentEncoding.test(value))\n return false;\n return URL.canParse(NarrowIpvFuture(value));\n }\n\n // node_modules/typebox/build/format/json_pointer_uri_fragment.mjs\n var JsonPointerUriFragment = /^#(?:\\/(?:[a-z0-9_\\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;\n function IsJsonPointerUriFragment(value) {\n return JsonPointerUriFragment.test(value);\n }\n\n // node_modules/typebox/build/format/json_pointer.mjs\n var JsonPointer = /^(?:\\/(?:[^~/]|~0|~1)*)*$/;\n function IsJsonPointer(value) {\n return JsonPointer.test(value);\n }\n\n // node_modules/typebox/build/format/regex.mjs\n function IsRegex(value) {\n try {\n new RegExp(value, \"u\");\n return true;\n } catch {\n return false;\n }\n }\n\n // node_modules/typebox/build/format/relative_json_pointer.mjs\n var RelativeJsonPointer = /^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/;\n function IsRelativeJsonPointer(value) {\n return RelativeJsonPointer.test(value);\n }\n\n // node_modules/typebox/build/format/uri_reference.mjs\n var UriReference = /^(?:[a-z][a-z0-9+\\-.]*:(?:\\/\\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:[\\da-f]{1,4}:){6}(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|::(?:[\\da-f]{1,4}:){5}(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:[\\da-f]{1,4})?::(?:[\\da-f]{1,4}:){4}(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[\\da-f]{1,4}:){0,1}[\\da-f]{1,4})?::(?:[\\da-f]{1,4}:){3}(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[\\da-f]{1,4}:){0,2}[\\da-f]{1,4})?::(?:[\\da-f]{1,4}:){2}(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[\\da-f]{1,4}:){0,3}[\\da-f]{1,4})?::[\\da-f]{1,4}:(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[\\da-f]{1,4}:){0,4}[\\da-f]{1,4})?::(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[\\da-f]{1,4}:){0,5}[\\da-f]{1,4})?::[\\da-f]{1,4}|(?:(?:[\\da-f]{1,4}:){0,6}[\\da-f]{1,4})?::)|v[0-9a-f]+\\.[-a-z0-9._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:\\/\\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:[\\da-f]{1,4}:){6}(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|::(?:[\\da-f]{1,4}:){5}(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:[\\da-f]{1,4})?::(?:[\\da-f]{1,4}:){4}(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[\\da-f]{1,4}:){0,1}[\\da-f]{1,4})?::(?:[\\da-f]{1,4}:){3}(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[\\da-f]{1,4}:){0,2}[\\da-f]{1,4})?::(?:[\\da-f]{1,4}:){2}(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[\\da-f]{1,4}:){0,3}[\\da-f]{1,4})?::[\\da-f]{1,4}:(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[\\da-f]{1,4}:){0,4}[\\da-f]{1,4})?::(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[\\da-f]{1,4}:){0,5}[\\da-f]{1,4})?::[\\da-f]{1,4}|(?:(?:[\\da-f]{1,4}:){0,6}[\\da-f]{1,4})?::)|v[0-9a-f]+\\.[-a-z0-9._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=@]|%[0-9a-f]{2})+(?:\\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;\n function IsUriReference(value) {\n return UriReference.test(value);\n }\n\n // node_modules/typebox/build/format/uri_template.mjs\n var UriTemplate = /^(?:(?:[^\\x00-\\x20\"<>%\\\\^`{|}\\x7f]|%[0-9a-f]{2})|\\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\\d{0,3}|\\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\\d{0,3}|\\*)?)*\\})*$/i;\n function IsUriTemplate(value) {\n return UriTemplate.test(value);\n }\n\n // node_modules/typebox/build/format/uri.mjs\n var Uri = /^[a-z][a-z0-9+\\-.]*:(?:\\/\\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:[\\da-f]{1,4}:){6}(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|::(?:[\\da-f]{1,4}:){5}(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:[\\da-f]{1,4})?::(?:[\\da-f]{1,4}:){4}(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[\\da-f]{1,4}:){0,1}[\\da-f]{1,4})?::(?:[\\da-f]{1,4}:){3}(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[\\da-f]{1,4}:){0,2}[\\da-f]{1,4})?::(?:[\\da-f]{1,4}:){2}(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[\\da-f]{1,4}:){0,3}[\\da-f]{1,4})?::[\\da-f]{1,4}:(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[\\da-f]{1,4}:){0,4}[\\da-f]{1,4})?::(?:[\\da-f]{1,4}:[\\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d))|(?:(?:[\\da-f]{1,4}:){0,5}[\\da-f]{1,4})?::[\\da-f]{1,4}|(?:(?:[\\da-f]{1,4}:){0,6}[\\da-f]{1,4})?::)|v[0-9a-f]+\\.[-a-z0-9._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;\n function IsUri(value) {\n return Uri.test(value);\n }\n\n // node_modules/typebox/build/format/url.mjs\n function IsUrl(value) {\n return URL.canParse(value);\n }\n\n // node_modules/typebox/build/format/uuid.mjs\n var Uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;\n function IsUuid(value) {\n return Uuid.test(value);\n }\n\n // node_modules/typebox/build/format/_registry.mjs\n var formats = /* @__PURE__ */ new Map();\n function Clear() {\n formats.clear();\n }\n function Entries3() {\n return [...formats.entries()];\n }\n function Set3(format, check) {\n formats.set(format, check);\n }\n function Has(format) {\n return formats.has(format);\n }\n function Get2(format) {\n return formats.get(format);\n }\n function Test(format, value) {\n return formats.get(format)?.(value) ?? true;\n }\n function Reset2() {\n Clear();\n formats.set(\"date-time\", IsDateTime);\n formats.set(\"date\", IsDate2);\n formats.set(\"duration\", IsDuration);\n formats.set(\"email\", IsEmail);\n formats.set(\"hostname\", IsHostname2);\n formats.set(\"idn-email\", IsIdnEmail);\n formats.set(\"idn-hostname\", IsIdnHostname2);\n formats.set(\"ipv4\", IsIPv4);\n formats.set(\"ipv6\", IsIPv6);\n formats.set(\"iri-reference\", IsIriReference);\n formats.set(\"iri\", IsIri);\n formats.set(\"json-pointer-uri-fragment\", IsJsonPointerUriFragment);\n formats.set(\"json-pointer\", IsJsonPointer);\n formats.set(\"regex\", IsRegex);\n formats.set(\"relative-json-pointer\", IsRelativeJsonPointer);\n formats.set(\"time\", IsTime);\n formats.set(\"uri-reference\", IsUriReference);\n formats.set(\"uri-template\", IsUriTemplate);\n formats.set(\"uri\", IsUri);\n formats.set(\"url\", IsUrl);\n formats.set(\"uuid\", IsUuid);\n }\n Reset2();\n\n // node_modules/typebox/build/schema/engine/format.mjs\n function BuildFormat(_stack, _context, schema, value) {\n return emit_exports.Call(emit_exports.Member(\"Format\", \"Test\"), [emit_exports.Constant(schema.format), value]);\n }\n function CheckFormat(_stack, _context, schema, value) {\n return format_exports.Test(schema.format, value);\n }\n function ErrorFormat(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckFormat(stack, context2, schema, value) || context2.AddError({\n keyword: \"format\",\n schemaPath,\n instancePath,\n params: { format: schema.format }\n });\n }\n\n // node_modules/typebox/build/schema/engine/if.mjs\n function BuildIf(stack, context2, schema, value) {\n const thenSchema = IsThen(schema) ? schema.then : true;\n const elseSchema = IsElse(schema) ? schema.else : true;\n return emit_exports.Ternary(BuildSchema(stack, context2, schema.if, value), BuildSchema(stack, context2, thenSchema, value), BuildSchema(stack, context2, elseSchema, value));\n }\n function CheckIf(stack, context2, schema, value) {\n const thenSchema = IsThen(schema) ? schema.then : true;\n const elseSchema = IsElse(schema) ? schema.else : true;\n return CheckSchema(stack, context2, schema.if, value) ? CheckSchema(stack, context2, thenSchema, value) : CheckSchema(stack, context2, elseSchema, value);\n }\n function ErrorIf(stack, context2, schemaPath, instancePath, schema, value) {\n const thenSchema = IsThen(schema) ? schema.then : true;\n const elseSchema = IsElse(schema) ? schema.else : true;\n const trueContext = new ErrorContext();\n const isIf = ErrorSchema(stack, trueContext, `${schemaPath}/if`, instancePath, schema.if, value) ? ErrorSchema(stack, trueContext, `${schemaPath}/then`, instancePath, thenSchema, value) || context2.AddError({\n keyword: \"if\",\n schemaPath,\n instancePath,\n params: { failingKeyword: \"then\" }\n }) : ErrorSchema(stack, context2, `${schemaPath}/else`, instancePath, elseSchema, value) || context2.AddError({\n keyword: \"if\",\n schemaPath,\n instancePath,\n params: { failingKeyword: \"else\" }\n });\n if (isIf)\n context2.Merge([trueContext]);\n return isIf;\n }\n\n // node_modules/typebox/build/schema/engine/items.mjs\n function BuildItemsSizedStandard(stack, context2, schema, value) {\n return emit_exports.ReduceAnd(schema.items.map((schema2, index3) => {\n const isLength = emit_exports.IsLessEqualThan(emit_exports.Member(value, \"length\"), emit_exports.Constant(index3));\n const isSchema = BuildSchemaPushStack(stack, context2, schema2, `${value}[${index3}]`);\n const addIndex = context2.AddIndex(emit_exports.Constant(index3));\n return emit_exports.Or(isLength, emit_exports.And(isSchema, addIndex));\n }));\n }\n function BuildItemsSizedFast(stack, context2, schema, value) {\n return emit_exports.ReduceAnd(schema.items.map((schema2, index3) => {\n const isLength = emit_exports.IsLessEqualThan(emit_exports.Member(value, \"length\"), emit_exports.Constant(index3));\n const isSchema = BuildSchemaPushStack(stack, context2, schema2, `${value}[${index3}]`);\n return emit_exports.Or(isLength, isSchema);\n }));\n }\n function BuildItemsSized(stack, context2, schema, value) {\n return context2.UseUnevaluated() ? BuildItemsSizedStandard(stack, context2, schema, value) : BuildItemsSizedFast(stack, context2, schema, value);\n }\n function CheckItemsSized(stack, context2, schema, value) {\n return guard_exports.Every(schema.items, 0, (schema2, index3) => {\n return guard_exports.IsLessEqualThan(value.length, index3) || CheckSchemaPushStack(stack, context2, schema2, value[index3]) && context2.AddIndex(index3);\n });\n }\n function ErrorItemsSized(stack, context2, schemaPath, instancePath, schema, value) {\n return guard_exports.EveryAll(schema.items, 0, (schema2, index3) => {\n const nextSchemaPath = `${schemaPath}/items/${index3}`;\n const nextInstancePath = `${instancePath}/${index3}`;\n return guard_exports.IsLessEqualThan(value.length, index3) || ErrorSchemaPushStack(stack, context2, nextSchemaPath, nextInstancePath, schema2, value[index3]) && context2.AddIndex(index3);\n });\n }\n function BuildItemsUnsizedStandard(stack, context2, schema, value) {\n const offset = IsPrefixItems(schema) ? schema.prefixItems.length : 0;\n const isSchema = BuildSchemaPushStack(stack, context2, schema.items, \"element\");\n const addIndex = context2.AddIndex(\"index\");\n return emit_exports.Every(value, emit_exports.Constant(offset), [\"element\", \"index\"], emit_exports.And(isSchema, addIndex));\n }\n function BuildItemsUnsizedFast(stack, context2, schema, value) {\n const offset = IsPrefixItems(schema) ? schema.prefixItems.length : 0;\n const isSchema = BuildSchemaPushStack(stack, context2, schema.items, \"element\");\n return emit_exports.Every(value, emit_exports.Constant(offset), [\"element\", \"index\"], isSchema);\n }\n function BuildItemsUnsized(stack, context2, schema, value) {\n return context2.UseUnevaluated() ? BuildItemsUnsizedStandard(stack, context2, schema, value) : BuildItemsUnsizedFast(stack, context2, schema, value);\n }\n function CheckItemsUnsized(stack, context2, schema, value) {\n const offset = IsPrefixItems(schema) ? schema.prefixItems.length : 0;\n return guard_exports.Every(value, offset, (element, index3) => {\n return CheckSchemaPushStack(stack, context2, schema.items, element) && context2.AddIndex(index3);\n });\n }\n function ErrorItemsUnsized(stack, context2, schemaPath, instancePath, schema, value) {\n const offset = IsPrefixItems(schema) ? schema.prefixItems.length : 0;\n return guard_exports.EveryAll(value, offset, (element, index3) => {\n const nextSchemaPath = `${schemaPath}/items`;\n const nextInstancePath = `${instancePath}/${index3}`;\n return ErrorSchemaPushStack(stack, context2, nextSchemaPath, nextInstancePath, schema.items, element) && context2.AddIndex(index3);\n });\n }\n function BuildItems(stack, context2, schema, value) {\n return IsItemsSized(schema) ? BuildItemsSized(stack, context2, schema, value) : BuildItemsUnsized(stack, context2, schema, value);\n }\n function CheckItems(stack, context2, schema, value) {\n return IsItemsSized(schema) ? CheckItemsSized(stack, context2, schema, value) : CheckItemsUnsized(stack, context2, schema, value);\n }\n function ErrorItems(stack, context2, schemaPath, instancePath, schema, value) {\n return IsItemsSized(schema) ? ErrorItemsSized(stack, context2, schemaPath, instancePath, schema, value) : ErrorItemsUnsized(stack, context2, schemaPath, instancePath, schema, value);\n }\n\n // node_modules/typebox/build/schema/engine/maxContains.mjs\n function IsValid3(schema) {\n return IsContains(schema);\n }\n function BuildMaxContains(stack, context2, schema, value) {\n if (!IsValid3(schema))\n return emit_exports.Constant(true);\n const [item] = [Unique()];\n const count = emit_exports.Counted(value, [item, \"_\"], BuildSchema(stack, context2, schema.contains, item));\n return emit_exports.IsLessEqualThan(count, emit_exports.Constant(schema.maxContains));\n }\n function CheckMaxContains(stack, context2, schema, value) {\n if (!IsValid3(schema))\n return true;\n const count = guard_exports.Counted(value, (item) => CheckSchema(stack, context2, schema.contains, item));\n return guard_exports.IsLessEqualThan(count, schema.maxContains);\n }\n function ErrorMaxContains(stack, context2, schemaPath, instancePath, schema, value) {\n const minContains = IsMinContains(schema) ? schema.minContains : 1;\n return CheckMaxContains(stack, context2, schema, value) || context2.AddError({\n keyword: \"contains\",\n schemaPath,\n instancePath,\n params: { minContains, maxContains: schema.maxContains }\n });\n }\n\n // node_modules/typebox/build/schema/engine/maximum.mjs\n function BuildMaximum(_stack, _context, schema, value) {\n return emit_exports.IsLessEqualThan(value, emit_exports.Constant(schema.maximum));\n }\n function CheckMaximum(_stack, _context, schema, value) {\n return guard_exports.IsLessEqualThan(value, schema.maximum);\n }\n function ErrorMaximum(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckMaximum(stack, context2, schema, value) || context2.AddError({\n keyword: \"maximum\",\n schemaPath,\n instancePath,\n params: { comparison: \"<=\", limit: schema.maximum }\n });\n }\n\n // node_modules/typebox/build/schema/engine/maxItems.mjs\n function BuildMaxItems(_stack, _context, schema, value) {\n return emit_exports.IsLessEqualThan(emit_exports.Member(value, \"length\"), emit_exports.Constant(schema.maxItems));\n }\n function CheckMaxItems(_stack, _context, schema, value) {\n return guard_exports.IsLessEqualThan(value.length, schema.maxItems);\n }\n function ErrorMaxItems(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckMaxItems(stack, context2, schema, value) || context2.AddError({\n keyword: \"maxItems\",\n schemaPath,\n instancePath,\n params: { limit: schema.maxItems }\n });\n }\n\n // node_modules/typebox/build/schema/engine/maxLength.mjs\n function BuildMaxLength(_stack, _context, schema, value) {\n return emit_exports.IsMaxLength(value, emit_exports.Constant(schema.maxLength));\n }\n function CheckMaxLength(_stack, _context, schema, value) {\n return guard_exports.IsMaxLength(value, schema.maxLength);\n }\n function ErrorMaxLength(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckMaxLength(stack, context2, schema, value) || context2.AddError({\n keyword: \"maxLength\",\n schemaPath,\n instancePath,\n params: { limit: schema.maxLength }\n });\n }\n\n // node_modules/typebox/build/schema/engine/maxProperties.mjs\n function BuildMaxProperties(_stack, _context, schema, value) {\n return emit_exports.IsLessEqualThan(emit_exports.Member(emit_exports.Keys(value), \"length\"), emit_exports.Constant(schema.maxProperties));\n }\n function CheckMaxProperties(_stack, _context, schema, value) {\n return guard_exports.IsLessEqualThan(guard_exports.Keys(value).length, schema.maxProperties);\n }\n function ErrorMaxProperties(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckMaxProperties(stack, context2, schema, value) || context2.AddError({\n keyword: \"maxProperties\",\n schemaPath,\n instancePath,\n params: { limit: schema.maxProperties }\n });\n }\n\n // node_modules/typebox/build/schema/engine/minContains.mjs\n function IsValid4(schema) {\n return IsContains(schema);\n }\n function BuildMinContainsStandard(stack, context2, schema, value) {\n const [item, index3] = [Unique(), Unique()];\n const count = emit_exports.Counted(value, [item, index3], emit_exports.And(BuildSchema(stack, context2, schema.contains, item), context2.AddIndex(index3)));\n return emit_exports.IsGreaterEqualThan(count, emit_exports.Constant(schema.minContains));\n }\n function BuildMinContainsFast(stack, context2, schema, value) {\n const [item] = [Unique()];\n const count = emit_exports.Counted(value, [item, \"_\"], BuildSchema(stack, context2, schema.contains, item));\n return emit_exports.IsGreaterEqualThan(count, emit_exports.Constant(schema.minContains));\n }\n function BuildMinContains(stack, context2, schema, value) {\n if (!IsValid4(schema))\n return emit_exports.Constant(true);\n return context2.UseUnevaluated() ? BuildMinContainsStandard(stack, context2, schema, value) : BuildMinContainsFast(stack, context2, schema, value);\n }\n function CheckMinContains(stack, context2, schema, value) {\n if (!IsValid4(schema))\n return true;\n const count = guard_exports.Counted(value, (item, index3) => CheckSchema(stack, context2, schema.contains, item) && context2.AddIndex(index3));\n return guard_exports.IsGreaterEqualThan(count, schema.minContains);\n }\n function ErrorMinContains(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckMinContains(stack, context2, schema, value) || context2.AddError({\n keyword: \"contains\",\n schemaPath,\n instancePath,\n params: { minContains: schema.minContains }\n });\n }\n\n // node_modules/typebox/build/schema/engine/minimum.mjs\n function BuildMinimum(_stack, _context, schema, value) {\n return emit_exports.IsGreaterEqualThan(value, emit_exports.Constant(schema.minimum));\n }\n function CheckMinimum(_stack, _context, schema, value) {\n return guard_exports.IsGreaterEqualThan(value, schema.minimum);\n }\n function ErrorMinimum(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckMinimum(stack, context2, schema, value) || context2.AddError({\n keyword: \"minimum\",\n schemaPath,\n instancePath,\n params: { comparison: \">=\", limit: schema.minimum }\n });\n }\n\n // node_modules/typebox/build/schema/engine/minItems.mjs\n function BuildMinItems(_stack, _context, schema, value) {\n return emit_exports.IsGreaterEqualThan(emit_exports.Member(value, \"length\"), emit_exports.Constant(schema.minItems));\n }\n function CheckMinItems(_stack, _context, schema, value) {\n return guard_exports.IsGreaterEqualThan(value.length, schema.minItems);\n }\n function ErrorMinItems(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckMinItems(stack, context2, schema, value) || context2.AddError({\n keyword: \"minItems\",\n schemaPath,\n instancePath,\n params: { limit: schema.minItems }\n });\n }\n\n // node_modules/typebox/build/schema/engine/minLength.mjs\n function BuildMinLength(_stack, _context, schema, value) {\n return emit_exports.IsMinLength(value, emit_exports.Constant(schema.minLength));\n }\n function CheckMinLength(_stack, _context, schema, value) {\n return guard_exports.IsMinLength(value, schema.minLength);\n }\n function ErrorMinLength(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckMinLength(stack, context2, schema, value) || context2.AddError({\n keyword: \"minLength\",\n schemaPath,\n instancePath,\n params: { limit: schema.minLength }\n });\n }\n\n // node_modules/typebox/build/schema/engine/minProperties.mjs\n function BuildMinProperties(_stack, _context, schema, value) {\n return emit_exports.IsGreaterEqualThan(emit_exports.Member(emit_exports.Keys(value), \"length\"), emit_exports.Constant(schema.minProperties));\n }\n function CheckMinProperties(_stack, _context, schema, value) {\n return guard_exports.IsGreaterEqualThan(guard_exports.Keys(value).length, schema.minProperties);\n }\n function ErrorMinProperties(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckMinProperties(stack, context2, schema, value) || context2.AddError({\n keyword: \"minProperties\",\n schemaPath,\n instancePath,\n params: { limit: schema.minProperties }\n });\n }\n\n // node_modules/typebox/build/schema/engine/multipleOf.mjs\n function BuildMultipleOf(_stack, _context, schema, value) {\n return emit_exports.MultipleOf(value, emit_exports.Constant(schema.multipleOf));\n }\n function CheckMultipleOf(_stack, _context, schema, value) {\n return guard_exports.IsMultipleOf(value, schema.multipleOf);\n }\n function ErrorMultipleOf(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckMultipleOf(stack, context2, schema, value) || context2.AddError({\n keyword: \"multipleOf\",\n schemaPath,\n instancePath,\n params: { multipleOf: schema.multipleOf }\n });\n }\n\n // node_modules/typebox/build/schema/engine/not.mjs\n function BuildNotStandard(stack, context2, schema, value) {\n return Reducer(stack, context2, [schema.not], value, emit_exports.Not(emit_exports.IsEqual(emit_exports.Member(\"results\", \"length\"), emit_exports.Constant(1))));\n }\n function BuildNotFast(stack, context2, schema, value) {\n return emit_exports.Not(BuildSchema(stack, context2, schema.not, value));\n }\n function BuildNot(stack, context2, schema, value) {\n return context2.UseUnevaluated() ? BuildNotStandard(stack, context2, schema, value) : BuildNotFast(stack, context2, schema, value);\n }\n function CheckNot(stack, context2, schema, value) {\n const nextContext = new CheckContext();\n const isSchema = !CheckSchema(stack, nextContext, schema.not, value);\n const isNot = isSchema && context2.Merge([nextContext]);\n return isNot;\n }\n function ErrorNot(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckNot(stack, context2, schema, value) || context2.AddError({\n keyword: \"not\",\n schemaPath,\n instancePath,\n params: {}\n });\n }\n\n // node_modules/typebox/build/schema/engine/oneOf.mjs\n function BuildOneOfStandard(stack, context2, schema, value) {\n return Reducer(stack, context2, schema.oneOf, value, emit_exports.IsEqual(emit_exports.Member(\"results\", \"length\"), emit_exports.Constant(1)));\n }\n function BuildOneOfFast(stack, context2, schema, value) {\n const [result] = [Unique()];\n const results = emit_exports.ArrayLiteral(schema.oneOf.map((schema2) => BuildSchema(stack, context2, schema2, value)));\n const count = emit_exports.Counted(results, [result, \"_\"], emit_exports.IsEqual(result, emit_exports.Constant(true)));\n return emit_exports.IsEqual(count, emit_exports.Constant(1));\n }\n function BuildOneOf(stack, context2, schema, value) {\n return context2.UseUnevaluated() ? BuildOneOfStandard(stack, context2, schema, value) : BuildOneOfFast(stack, context2, schema, value);\n }\n function CheckOneOf(stack, context2, schema, value) {\n const passedContexts = schema.oneOf.reduce((result, schema2) => {\n const nextContext = new CheckContext();\n return CheckSchema(stack, nextContext, schema2, value) ? [...result, nextContext] : result;\n }, []);\n return guard_exports.IsEqual(passedContexts.length, 1) && context2.Merge(passedContexts);\n }\n function ErrorOneOf(stack, context2, schemaPath, instancePath, schema, value) {\n const failedContexts = [];\n const passingSchemas = [];\n const passedContexts = schema.oneOf.reduce((result, schema2, index3) => {\n const nextContext = new ErrorContext();\n const nextSchemaPath = `${schemaPath}/oneOf/${index3}`;\n const isSchema = ErrorSchema(stack, nextContext, nextSchemaPath, instancePath, schema2, value);\n if (isSchema)\n passingSchemas.push(index3);\n if (!isSchema)\n failedContexts.push(nextContext);\n return isSchema ? [...result, nextContext] : result;\n }, []);\n const isOneOf = guard_exports.IsEqual(passedContexts.length, 1) && context2.Merge(passedContexts);\n if (!isOneOf && guard_exports.IsEqual(passingSchemas.length, 0))\n failedContexts.forEach((failed) => failed.GetErrors().forEach((error) => context2.AddError(error)));\n return isOneOf || context2.AddError({\n keyword: \"oneOf\",\n schemaPath,\n instancePath,\n params: { passingSchemas }\n });\n }\n\n // node_modules/typebox/build/schema/engine/pattern.mjs\n function BuildPattern(_stack, _context, schema, value) {\n const regexp = CreateVariable(guard_exports.IsString(schema.pattern) ? UnicodeRegExp(schema.pattern) : schema.pattern);\n return emit_exports.Call(emit_exports.Member(regexp, \"test\"), [value]);\n }\n function CheckPattern(_stack, _context, schema, value) {\n const regexp = guard_exports.IsString(schema.pattern) ? UnicodeRegExp(schema.pattern) : schema.pattern;\n return regexp.test(value);\n }\n function ErrorPattern(stack, context2, schemaPath, instancePath, schema, value) {\n return CheckPattern(stack, context2, schema, value) || context2.AddError({\n keyword: \"pattern\",\n schemaPath,\n instancePath,\n params: { pattern: schema.pattern }\n });\n }\n\n // node_modules/typebox/build/schema/engine/patternProperties.mjs\n function BuildPatternProperties(stack, context2, schema, value) {\n return emit_exports.ReduceAnd(guard_exports.Entries(schema.patternProperties).map(([pattern, schema2]) => {\n const [key, prop] = [Unique(), Unique()];\n const regexp = CreateVariable(UnicodeRegExp(pattern));\n const notKey = emit_exports.Not(emit_exports.Call(emit_exports.Member(regexp, \"test\"), [key]));\n const isSchema = BuildSchemaPushStack(stack, context2, schema2, prop);\n const addKey = context2.AddKey(key);\n const guarded = context2.UseUnevaluated() ? emit_exports.Or(notKey, emit_exports.And(isSchema, addKey)) : emit_exports.Or(notKey, isSchema);\n return emit_exports.Every(emit_exports.Entries(value), emit_exports.Constant(0), [`[${key}, ${prop}]`, \"_\"], guarded);\n }));\n }\n function CheckPatternProperties(stack, context2, schema, value) {\n return guard_exports.Every(guard_exports.Entries(schema.patternProperties), 0, ([pattern, schema2]) => {\n const regexp = UnicodeRegExp(pattern);\n return guard_exports.Every(guard_exports.Entries(value), 0, ([key, prop]) => {\n return !regexp.test(key) || CheckSchemaPushStack(stack, context2, schema2, prop) && context2.AddKey(key);\n });\n });\n }\n function ErrorPatternProperties(stack, context2, schemaPath, instancePath, schema, value) {\n return guard_exports.EveryAll(guard_exports.Entries(schema.patternProperties), 0, ([pattern, schema2]) => {\n const nextSchemaPath = `${schemaPath}/patternProperties/${pattern}`;\n const regexp = UnicodeRegExp(pattern);\n return guard_exports.EveryAll(guard_exports.Entries(value), 0, ([key, value2]) => {\n const nextInstancePath = `${instancePath}/${key}`;\n const notKey = !regexp.test(key);\n return notKey || ErrorSchemaPushStack(stack, context2, nextSchemaPath, nextInstancePath, schema2, value2) && context2.AddKey(key);\n });\n });\n }\n\n // node_modules/typebox/build/schema/engine/prefixItems.mjs\n function BuildPrefixItems(stack, context2, schema, value) {\n return emit_exports.ReduceAnd(schema.prefixItems.map((schema2, index3) => {\n const isLength = emit_exports.IsLessEqualThan(emit_exports.Member(value, \"length\"), emit_exports.Constant(index3));\n const isSchema = BuildSchemaPushStack(stack, context2, schema2, `${value}[${index3}]`);\n const addIndex = context2.AddIndex(emit_exports.Constant(index3));\n const guarded = context2.UseUnevaluated() ? emit_exports.And(isSchema, addIndex) : isSchema;\n return emit_exports.Or(isLength, guarded);\n }));\n }\n function CheckPrefixItems(stack, context2, schema, value) {\n return guard_exports.IsEqual(value.length, 0) || guard_exports.Every(schema.prefixItems, 0, (schema2, index3) => {\n return guard_exports.IsLessEqualThan(value.length, index3) || CheckSchemaPushStack(stack, context2, schema2, value[index3]) && context2.AddIndex(index3);\n });\n }\n function ErrorPrefixItems(stack, context2, schemaPath, instancePath, schema, value) {\n return guard_exports.IsEqual(value.length, 0) || guard_exports.EveryAll(schema.prefixItems, 0, (schema2, index3) => {\n const nextSchemaPath = `${schemaPath}/prefixItems/${index3}`;\n const nextInstancePath = `${instancePath}/${index3}`;\n return guard_exports.IsLessEqualThan(value.length, index3) || ErrorSchemaPushStack(stack, context2, nextSchemaPath, nextInstancePath, schema2, value[index3]) && context2.AddIndex(index3);\n });\n }\n\n // node_modules/typebox/build/schema/engine/_exact_optional.mjs\n function IsExactOptional(required, key) {\n return required.includes(key) || settings_exports.Get().exactOptionalPropertyTypes;\n }\n function InexactOptionalBuild(value, key) {\n return emit_exports.IsUndefined(emit_exports.Member(value, key));\n }\n function InexactOptionalCheck(value, key) {\n return guard_exports.IsUndefined(value[key]);\n }\n\n // node_modules/typebox/build/schema/engine/properties.mjs\n function BuildProperties(stack, context2, schema, value) {\n const required = IsRequired(schema) ? schema.required : [];\n const everyKey = guard_exports.Entries(schema.properties).map(([key, schema2]) => {\n const notKey = emit_exports.Not(emit_exports.HasPropertyKey(value, emit_exports.Constant(key)));\n const isSchema = BuildSchemaPushStack(stack, context2, schema2, emit_exports.Member(value, key));\n const addKey = context2.AddKey(emit_exports.Constant(key));\n const guarded = context2.UseUnevaluated() ? emit_exports.And(isSchema, addKey) : isSchema;\n const isProperty = required.includes(key) ? guarded : emit_exports.Or(notKey, guarded);\n return IsExactOptional(required, key) ? isProperty : emit_exports.Or(InexactOptionalBuild(value, key), isProperty);\n });\n return emit_exports.ReduceAnd(everyKey);\n }\n function CheckProperties(stack, context2, schema, value) {\n const required = IsRequired(schema) ? schema.required : [];\n const isProperties = guard_exports.Every(guard_exports.Entries(schema.properties), 0, ([key, schema2]) => {\n const isProperty = !guard_exports.HasPropertyKey(value, key) || CheckSchemaPushStack(stack, context2, schema2, value[key]) && context2.AddKey(key);\n return IsExactOptional(required, key) ? isProperty : InexactOptionalCheck(value, key) || isProperty;\n });\n return isProperties;\n }\n function ErrorProperties(stack, context2, schemaPath, instancePath, schema, value) {\n const required = IsRequired(schema) ? schema.required : [];\n const isProperties = guard_exports.EveryAll(guard_exports.Entries(schema.properties), 0, ([key, schema2]) => {\n const nextSchemaPath = `${schemaPath}/properties/${key}`;\n const nextInstancePath = `${instancePath}/${key}`;\n const isProperty = () => !guard_exports.HasPropertyKey(value, key) || ErrorSchemaPushStack(stack, context2, nextSchemaPath, nextInstancePath, schema2, value[key]) && context2.AddKey(key);\n return IsExactOptional(required, key) ? isProperty() : InexactOptionalCheck(value, key) || isProperty();\n });\n return isProperties;\n }\n\n // node_modules/typebox/build/schema/engine/propertyNames.mjs\n function BuildPropertyNames(stack, context2, schema, value) {\n const [key, _index] = [Unique(), Unique()];\n return emit_exports.Every(emit_exports.Keys(value), emit_exports.Constant(0), [key, _index], BuildSchema(stack, context2, schema.propertyNames, key));\n }\n function CheckPropertyNames(stack, context2, schema, value) {\n return guard_exports.Every(guard_exports.Keys(value), 0, (key, _index) => CheckSchema(stack, context2, schema.propertyNames, key));\n }\n function ErrorPropertyNames(stack, context2, schemaPath, instancePath, schema, value) {\n const propertyNames = [];\n const isPropertyNames = guard_exports.EveryAll(guard_exports.Keys(value), 0, (key, _index) => {\n const nextInstancePath = `${instancePath}/${key}`;\n const nextSchemaPath = `${schemaPath}/propertyNames`;\n const isPropertyName = ErrorSchema(stack, context2, nextSchemaPath, nextInstancePath, schema.propertyNames, key);\n if (!isPropertyName)\n propertyNames.push(key);\n return isPropertyName;\n });\n return isPropertyNames || context2.AddError({\n keyword: \"propertyNames\",\n schemaPath,\n instancePath,\n params: { propertyNames }\n });\n }\n\n // node_modules/typebox/build/schema/engine/recursiveRef.mjs\n function BuildRecursiveRef(stack, context2, schema, value) {\n const target = stack.RecursiveRef(schema) ?? false;\n return CreateFunction(stack, context2, target, value);\n }\n function CheckRecursiveRef(stack, context2, schema, value) {\n const target = stack.RecursiveRef(schema) ?? false;\n return IsSchema(target) && CheckSchema(stack, context2, target, value);\n }\n function ErrorRecursiveRef(stack, context2, _schemaPath, instancePath, schema, value) {\n const target = stack.RecursiveRef(schema) ?? false;\n return IsSchema(target) && ErrorSchema(stack, context2, \"#\", instancePath, target, value);\n }\n\n // node_modules/typebox/build/schema/engine/ref.mjs\n function BuildRefStandard(stack, context2, target, value) {\n const interior = emit_exports.ArrowFunction([\"context\", \"value\"], CreateFunction(stack, context2, target, \"value\"));\n const exterior = emit_exports.ArrowFunction([\"context\", \"value\"], emit_exports.Statements([\n emit_exports.ConstDeclaration(\"nextContext\", emit_exports.New(\"CheckContext\", [])),\n emit_exports.ConstDeclaration(\"result\", emit_exports.Call(interior, [\"nextContext\", \"value\"])),\n emit_exports.If(\"result\", context2.Merge(\"[nextContext]\")),\n emit_exports.Return(\"result\")\n ]));\n return emit_exports.Call(exterior, [\"context\", value]);\n }\n function BuildRefFast(stack, context2, target, value) {\n return CreateFunction(stack, context2, target, value);\n }\n function BuildRef(stack, context2, schema, value) {\n const target = stack.Ref(schema) ?? false;\n return context2.UseUnevaluated() ? BuildRefStandard(stack, context2, target, value) : BuildRefFast(stack, context2, target, value);\n }\n function CheckRef(stack, context2, schema, value) {\n const target = stack.Ref(schema) ?? false;\n const nextContext = new CheckContext();\n const result = IsSchema(target) && CheckSchema(stack, nextContext, target, value);\n if (result)\n context2.Merge([nextContext]);\n return result;\n }\n function ErrorRef(stack, context2, _schemaPath, instancePath, schema, value) {\n const target = stack.Ref(schema) ?? false;\n const nextContext = new ErrorContext();\n const result = IsSchema(target) && ErrorSchema(stack, nextContext, \"#\", instancePath, target, value);\n if (result)\n context2.Merge([nextContext]);\n if (!result)\n nextContext.GetErrors().forEach((error) => context2.AddError(error));\n return result;\n }\n\n // node_modules/typebox/build/schema/engine/required.mjs\n function BuildRequired(_stack, _context, schema, value) {\n return emit_exports.ReduceAnd(schema.required.map((key) => emit_exports.HasPropertyKey(value, emit_exports.Constant(key))));\n }\n function CheckRequired(_stack, _context, schema, value) {\n return guard_exports.Every(schema.required, 0, (key) => guard_exports.HasPropertyKey(value, key));\n }\n function ErrorRequired(_stack, context2, schemaPath, instancePath, schema, value) {\n const requiredProperties = [];\n const isRequired = guard_exports.EveryAll(schema.required, 0, (key) => {\n const hasKey = guard_exports.HasPropertyKey(value, key);\n if (!hasKey)\n requiredProperties.push(key);\n return hasKey;\n });\n return isRequired || context2.AddError({\n keyword: \"required\",\n schemaPath,\n instancePath,\n params: { requiredProperties }\n });\n }\n\n // node_modules/typebox/build/schema/engine/type.mjs\n function BuildTypeName(_stack, _context, type, value) {\n return (\n // jsonschema\n guard_exports.IsEqual(type, \"object\") ? emit_exports.IsObjectNotArray(value) : guard_exports.IsEqual(type, \"array\") ? emit_exports.IsArray(value) : guard_exports.IsEqual(type, \"boolean\") ? emit_exports.IsBoolean(value) : guard_exports.IsEqual(type, \"integer\") ? emit_exports.IsInteger(value) : guard_exports.IsEqual(type, \"number\") ? emit_exports.IsNumber(value) : guard_exports.IsEqual(type, \"null\") ? emit_exports.IsNull(value) : guard_exports.IsEqual(type, \"string\") ? emit_exports.IsString(value) : (\n // xschema\n guard_exports.IsEqual(type, \"bigint\") ? emit_exports.IsBigInt(value) : guard_exports.IsEqual(type, \"constructor\") ? emit_exports.IsConstructor(value) : guard_exports.IsEqual(type, \"function\") ? emit_exports.IsFunction(value) : guard_exports.IsEqual(type, \"symbol\") ? emit_exports.IsSymbol(value) : guard_exports.IsEqual(type, \"undefined\") ? emit_exports.IsUndefined(value) : guard_exports.IsEqual(type, \"void\") ? emit_exports.IsUndefined(value) : emit_exports.Constant(true)\n )\n );\n }\n function CheckTypeName(_stack, _context, type, _schema, value) {\n return (\n // jsonschema\n guard_exports.IsEqual(type, \"object\") ? guard_exports.IsObjectNotArray(value) : guard_exports.IsEqual(type, \"array\") ? guard_exports.IsArray(value) : guard_exports.IsEqual(type, \"boolean\") ? guard_exports.IsBoolean(value) : guard_exports.IsEqual(type, \"integer\") ? guard_exports.IsInteger(value) : guard_exports.IsEqual(type, \"number\") ? guard_exports.IsNumber(value) : guard_exports.IsEqual(type, \"null\") ? guard_exports.IsNull(value) : guard_exports.IsEqual(type, \"string\") ? guard_exports.IsString(value) : (\n // xschema\n guard_exports.IsEqual(type, \"bigint\") ? guard_exports.IsBigInt(value) : guard_exports.IsEqual(type, \"constructor\") ? guard_exports.IsConstructor(value) : guard_exports.IsEqual(type, \"function\") ? guard_exports.IsFunction(value) : guard_exports.IsEqual(type, \"symbol\") ? guard_exports.IsSymbol(value) : guard_exports.IsEqual(type, \"undefined\") ? guard_exports.IsUndefined(value) : guard_exports.IsEqual(type, \"void\") ? guard_exports.IsUndefined(value) : true\n )\n );\n }\n function BuildTypeNames(stack, context2, typenames, value) {\n return emit_exports.ReduceOr(typenames.map((type) => BuildTypeName(stack, context2, type, value)));\n }\n function CheckTypeNames(stack, context2, types, schema, value) {\n return guard_exports.Some(types, (type) => CheckTypeName(stack, context2, type, schema, value));\n }\n function BuildType(stack, context2, schema, value) {\n return guard_exports.IsArray(schema.type) ? BuildTypeNames(stack, context2, schema.type, value) : BuildTypeName(stack, context2, schema.type, value);\n }\n function CheckType(stack, context2, schema, value) {\n return guard_exports.IsArray(schema.type) ? CheckTypeNames(stack, context2, schema.type, schema, value) : CheckTypeName(stack, context2, schema.type, schema, value);\n }\n function ErrorType(stack, context2, schemaPath, instancePath, schema, value) {\n const isType = guard_exports.IsArray(schema.type) ? CheckTypeNames(stack, context2, schema.type, schema, value) : CheckTypeName(stack, context2, schema.type, schema, value);\n return isType || context2.AddError({\n keyword: \"type\",\n schemaPath,\n instancePath,\n params: { type: schema.type }\n });\n }\n\n // node_modules/typebox/build/schema/engine/unevaluatedItems.mjs\n function BuildUnevaluatedItems(stack, context2, schema, value) {\n const [index3, item] = [Unique(), Unique()];\n const indices = emit_exports.Call(emit_exports.Member(\"context\", \"GetIndices\"), []);\n const hasIndex = emit_exports.Call(emit_exports.Member(\"indices\", \"has\"), [index3]);\n const isSchema = BuildSchema(stack, context2, schema.unevaluatedItems, item);\n const addIndex = emit_exports.Call(emit_exports.Member(\"context\", \"AddIndex\"), [index3]);\n const isEvery = emit_exports.Every(value, emit_exports.Constant(0), [item, index3], emit_exports.And(emit_exports.Or(hasIndex, isSchema), addIndex));\n return emit_exports.Call(emit_exports.ArrowFunction([\"context\"], emit_exports.Statements([\n emit_exports.ConstDeclaration(\"indices\", indices),\n emit_exports.Return(isEvery)\n ])), [\"context\"]);\n }\n function CheckUnevaluatedItems(stack, context2, schema, value) {\n const indices = context2.GetIndices();\n return guard_exports.Every(value, 0, (item, index3) => {\n return (indices.has(index3) || CheckSchema(stack, context2, schema.unevaluatedItems, item)) && context2.AddIndex(index3);\n });\n }\n function ErrorUnevaluatedItems(stack, context2, schemaPath, instancePath, schema, value) {\n const indices = context2.GetIndices();\n const unevaluatedItems = [];\n const isUnevaluatedItems = guard_exports.EveryAll(value, 0, (item, index3) => {\n const nextContext = new ErrorContext();\n const isEvaluatedItem = (indices.has(index3) || ErrorSchema(stack, nextContext, schemaPath, instancePath, schema.unevaluatedItems, item)) && context2.AddIndex(index3);\n if (!isEvaluatedItem)\n unevaluatedItems.push(index3);\n return isEvaluatedItem;\n });\n return isUnevaluatedItems || context2.AddError({\n keyword: \"unevaluatedItems\",\n schemaPath,\n instancePath,\n params: { unevaluatedItems }\n });\n }\n\n // node_modules/typebox/build/schema/engine/unevaluatedProperties.mjs\n function BuildUnevaluatedProperties(stack, context2, schema, value) {\n const [key, prop] = [Unique(), Unique()];\n const keys = emit_exports.Call(emit_exports.Member(\"context\", \"GetKeys\"), []);\n const hasKey = emit_exports.Call(emit_exports.Member(\"keys\", \"has\"), [key]);\n const addKey = emit_exports.Call(emit_exports.Member(\"context\", \"AddKey\"), [key]);\n const isSchema = BuildSchema(stack, context2, schema.unevaluatedProperties, prop);\n const isEvery = emit_exports.Every(emit_exports.Entries(value), emit_exports.Constant(0), [`[${key}, ${prop}]`, \"_\"], emit_exports.Or(hasKey, emit_exports.And(isSchema, addKey)));\n return emit_exports.Call(emit_exports.ArrowFunction([\"context\"], emit_exports.Statements([\n emit_exports.ConstDeclaration(\"keys\", keys),\n emit_exports.Return(isEvery)\n ])), [\"context\"]);\n }\n function CheckUnevaluatedProperties(stack, context2, schema, value) {\n const keys = context2.GetKeys();\n return guard_exports.Every(guard_exports.Entries(value), 0, ([key, prop]) => {\n return keys.has(key) || CheckSchema(stack, context2, schema.unevaluatedProperties, prop) && context2.AddKey(key);\n });\n }\n function ErrorUnevaluatedProperties(stack, context2, schemaPath, instancePath, schema, value) {\n const keys = context2.GetKeys();\n const unevaluatedProperties = [];\n const isUnevaluatedProperties = guard_exports.EveryAll(guard_exports.Entries(value), 0, ([key, prop]) => {\n const nextContext = new ErrorContext();\n const isEvaluatedProperty = keys.has(key) || ErrorSchema(stack, nextContext, schemaPath, instancePath, schema.unevaluatedProperties, prop) && context2.AddKey(key);\n if (!isEvaluatedProperty)\n unevaluatedProperties.push(key);\n return isEvaluatedProperty;\n });\n return isUnevaluatedProperties || context2.AddError({\n keyword: \"unevaluatedProperties\",\n schemaPath,\n instancePath,\n params: { unevaluatedProperties }\n });\n }\n\n // node_modules/typebox/build/system/hashing/hash.mjs\n var hash_exports = {};\n __export(hash_exports, {\n Hash: () => Hash,\n HashCode: () => HashCode\n });\n\n // node_modules/typebox/build/system/unreachable/unreachable.mjs\n function Unreachable() {\n throw new Error(\"Unreachable\");\n }\n\n // node_modules/typebox/build/system/hashing/hash.mjs\n function InstanceKeys(value) {\n const propertyKeys = /* @__PURE__ */ new Set();\n let current = value;\n while (current && current !== Object.prototype) {\n for (const key of Reflect.ownKeys(current)) {\n if (key !== \"constructor\" && typeof key !== \"symbol\")\n propertyKeys.add(key);\n }\n current = Object.getPrototypeOf(current);\n }\n return [...propertyKeys];\n }\n function IsIEEE754(value) {\n return typeof value === \"number\";\n }\n var ByteMarker;\n (function(ByteMarker2) {\n ByteMarker2[ByteMarker2[\"Array\"] = 0] = \"Array\";\n ByteMarker2[ByteMarker2[\"BigInt\"] = 1] = \"BigInt\";\n ByteMarker2[ByteMarker2[\"Boolean\"] = 2] = \"Boolean\";\n ByteMarker2[ByteMarker2[\"Date\"] = 3] = \"Date\";\n ByteMarker2[ByteMarker2[\"Constructor\"] = 4] = \"Constructor\";\n ByteMarker2[ByteMarker2[\"Function\"] = 5] = \"Function\";\n ByteMarker2[ByteMarker2[\"Null\"] = 6] = \"Null\";\n ByteMarker2[ByteMarker2[\"Number\"] = 7] = \"Number\";\n ByteMarker2[ByteMarker2[\"Object\"] = 8] = \"Object\";\n ByteMarker2[ByteMarker2[\"RegExp\"] = 9] = \"RegExp\";\n ByteMarker2[ByteMarker2[\"String\"] = 10] = \"String\";\n ByteMarker2[ByteMarker2[\"Symbol\"] = 11] = \"Symbol\";\n ByteMarker2[ByteMarker2[\"TypeArray\"] = 12] = \"TypeArray\";\n ByteMarker2[ByteMarker2[\"Undefined\"] = 13] = \"Undefined\";\n })(ByteMarker || (ByteMarker = {}));\n var Accumulator = BigInt(\"14695981039346656037\");\n var [Prime, Size] = [BigInt(\"1099511628211\"), BigInt(\n \"18446744073709551616\"\n /* 2 ^ 64 */\n )];\n var Bytes = Array.from({ length: 256 }).map((_, i) => BigInt(i));\n var F64 = new Float64Array(1);\n var F64In = new DataView(F64.buffer);\n var F64Out = new Uint8Array(F64.buffer);\n function FNV1A64_OP(byte) {\n Accumulator = Accumulator ^ Bytes[byte];\n Accumulator = Accumulator * Prime % Size;\n }\n function FromArray(value) {\n FNV1A64_OP(ByteMarker.Array);\n for (const item of value) {\n FromValue(item);\n }\n }\n function FromBigInt(value) {\n FNV1A64_OP(ByteMarker.BigInt);\n F64In.setBigInt64(0, value);\n for (const byte of F64Out) {\n FNV1A64_OP(byte);\n }\n }\n function FromBoolean(value) {\n FNV1A64_OP(ByteMarker.Boolean);\n FNV1A64_OP(value ? 1 : 0);\n }\n function FromConstructor(value) {\n FNV1A64_OP(ByteMarker.Constructor);\n FromValue(value.toString());\n }\n function FromDate(value) {\n FNV1A64_OP(ByteMarker.Date);\n FromValue(value.getTime());\n }\n function FromFunction(value) {\n FNV1A64_OP(ByteMarker.Function);\n FromValue(value.toString());\n }\n function FromNull(_value) {\n FNV1A64_OP(ByteMarker.Null);\n }\n function FromNumber(value) {\n FNV1A64_OP(ByteMarker.Number);\n F64In.setFloat64(\n 0,\n value,\n true\n /* little-endian */\n );\n for (const byte of F64Out) {\n FNV1A64_OP(byte);\n }\n }\n function FromObject(value) {\n FNV1A64_OP(ByteMarker.Object);\n for (const key of InstanceKeys(value).sort()) {\n FromValue(key);\n FromValue(value[key]);\n }\n }\n function FromRegExp(value) {\n FNV1A64_OP(ByteMarker.RegExp);\n FromString(value.toString());\n }\n var encoder = new TextEncoder();\n function FromString(value) {\n FNV1A64_OP(ByteMarker.String);\n for (const byte of encoder.encode(value)) {\n FNV1A64_OP(byte);\n }\n }\n function FromSymbol(value) {\n FNV1A64_OP(ByteMarker.Symbol);\n FromValue(value.toString());\n }\n function FromTypeArray(value) {\n FNV1A64_OP(ByteMarker.TypeArray);\n const buffer = new Uint8Array(value.buffer);\n for (let i = 0; i < buffer.length; i++) {\n FNV1A64_OP(buffer[i]);\n }\n }\n function FromUndefined(_value) {\n return FNV1A64_OP(ByteMarker.Undefined);\n }\n function FromValue(value) {\n return globals_exports.IsTypeArray(value) ? FromTypeArray(value) : globals_exports.IsDate(value) ? FromDate(value) : globals_exports.IsRegExp(value) ? FromRegExp(value) : globals_exports.IsBoolean(value) ? FromBoolean(value.valueOf()) : globals_exports.IsString(value) ? FromString(value.valueOf()) : globals_exports.IsNumber(value) ? FromNumber(value.valueOf()) : IsIEEE754(value) ? FromNumber(value) : guard_exports.IsArray(value) ? FromArray(value) : guard_exports.IsBoolean(value) ? FromBoolean(value) : guard_exports.IsBigInt(value) ? FromBigInt(value) : guard_exports.IsConstructor(value) ? FromConstructor(value) : guard_exports.IsNull(value) ? FromNull(value) : guard_exports.IsObject(value) ? FromObject(value) : guard_exports.IsString(value) ? FromString(value) : guard_exports.IsSymbol(value) ? FromSymbol(value) : guard_exports.IsUndefined(value) ? FromUndefined(value) : guard_exports.IsFunction(value) ? FromFunction(value) : Unreachable();\n }\n function HashCode(value) {\n Accumulator = BigInt(\"14695981039346656037\");\n FromValue(value);\n return Accumulator;\n }\n function Hash(value) {\n return HashCode(value).toString(16).padStart(16, \"0\");\n }\n\n // node_modules/typebox/build/schema/engine/uniqueItems.mjs\n function IsValid5(schema) {\n return !guard_exports.IsEqual(schema.uniqueItems, false);\n }\n function BuildUniqueItems(_stack, _context, schema, value) {\n if (!IsValid5(schema))\n return emit_exports.Constant(true);\n const set = emit_exports.Member(emit_exports.New(\"Set\", [emit_exports.Call(emit_exports.Member(value, \"map\"), [emit_exports.Member(\"Hashing\", \"Hash\")])]), \"size\");\n const isLength = emit_exports.Member(value, \"length\");\n return emit_exports.IsEqual(set, isLength);\n }\n function CheckUniqueItems(_stack, _context, schema, value) {\n if (!IsValid5(schema))\n return true;\n const set = new Set(value.map(hash_exports.Hash)).size;\n const isLength = value.length;\n return guard_exports.IsEqual(set, isLength);\n }\n function ErrorUniqueItems(_stack, context2, schemaPath, instancePath, schema, value) {\n if (!IsValid5(schema))\n return true;\n const set = /* @__PURE__ */ new Set();\n const duplicateItems = value.reduce((result, value2, index3) => {\n const hash = hash_exports.Hash(value2);\n if (set.has(hash))\n return [...result, index3];\n set.add(hash);\n return result;\n }, []);\n const isUniqueItems = guard_exports.IsEqual(duplicateItems.length, 0);\n return isUniqueItems || context2.AddError({\n keyword: \"uniqueItems\",\n schemaPath,\n instancePath,\n params: { duplicateItems }\n });\n }\n\n // node_modules/typebox/build/schema/engine/schema.mjs\n function HasTypeName(schema, typename) {\n return IsType(schema) && (guard_exports.IsArray(schema.type) && guard_exports.IsGreaterThan(schema.type.length, 0) && guard_exports.Every(schema.type, 0, (type) => guard_exports.IsEqual(type, typename)) || guard_exports.IsEqual(schema.type, typename));\n }\n function HasObjectType(schema) {\n return HasTypeName(schema, \"object\");\n }\n function HasObjectKeywords(schema) {\n return IsSchemaObject(schema) && (IsAdditionalProperties(schema) || IsDependencies(schema) || IsDependentRequired(schema) || IsDependentSchemas(schema) || IsProperties(schema) || IsPatternProperties(schema) || IsPropertyNames(schema) || IsMinProperties(schema) || IsMaxProperties(schema) || IsRequired(schema) || IsUnevaluatedProperties(schema));\n }\n function HasArrayType(schema) {\n return HasTypeName(schema, \"array\");\n }\n function HasArrayKeywords(schema) {\n return IsSchemaObject(schema) && (IsAdditionalItems(schema) || IsItems(schema) || IsContains(schema) || IsMaxContains(schema) || IsMaxItems(schema) || IsMinContains(schema) || IsMinItems(schema) || IsPrefixItems(schema) || IsUnevaluatedItems(schema) || IsUniqueItems(schema));\n }\n function HasStringType(schema) {\n return HasTypeName(schema, \"string\");\n }\n function HasStringKeywords(schema) {\n return IsSchemaObject(schema) && (IsMinLength4(schema) || IsMaxLength4(schema) || IsFormat(schema) || IsPattern(schema));\n }\n function HasNumberType(schema) {\n return HasTypeName(schema, \"number\") || HasTypeName(schema, \"bigint\");\n }\n function HasNumberKeywords(schema) {\n return IsSchemaObject(schema) && (IsMinimum(schema) || IsMaximum(schema) || IsExclusiveMaximum(schema) || IsExclusiveMinimum(schema) || IsMultipleOf2(schema));\n }\n function BuildSchemaPushStack(stack, context2, schema, value) {\n return context2.UseUnevaluated() ? emit_exports.And(emit_exports.And(context2.Push(), BuildSchema(stack, context2, schema, value)), context2.Pop()) : BuildSchema(stack, context2, schema, value);\n }\n function BuildSchema(stack, context2, schema, value) {\n stack.Push(schema);\n const conditions = [];\n if (IsSchemaBoolean(schema))\n return BuildSchemaBoolean(stack, context2, schema, value);\n if (IsType(schema))\n conditions.push(BuildType(stack, context2, schema, value));\n if (HasObjectKeywords(schema)) {\n const constraints = [];\n if (IsRequired(schema))\n constraints.push(BuildRequired(stack, context2, schema, value));\n if (IsAdditionalProperties(schema))\n constraints.push(BuildAdditionalProperties(stack, context2, schema, value));\n if (IsDependencies(schema))\n constraints.push(BuildDependencies(stack, context2, schema, value));\n if (IsDependentRequired(schema))\n constraints.push(BuildDependentRequired(stack, context2, schema, value));\n if (IsDependentSchemas(schema))\n constraints.push(BuildDependentSchemas(stack, context2, schema, value));\n if (IsPatternProperties(schema))\n constraints.push(BuildPatternProperties(stack, context2, schema, value));\n if (IsProperties(schema))\n constraints.push(BuildProperties(stack, context2, schema, value));\n if (IsPropertyNames(schema))\n constraints.push(BuildPropertyNames(stack, context2, schema, value));\n if (IsMinProperties(schema))\n constraints.push(BuildMinProperties(stack, context2, schema, value));\n if (IsMaxProperties(schema))\n constraints.push(BuildMaxProperties(stack, context2, schema, value));\n const reduced = emit_exports.ReduceAnd(constraints);\n const guarded = emit_exports.Or(emit_exports.Not(emit_exports.IsObjectNotArray(value)), reduced);\n conditions.push(HasObjectType(schema) ? reduced : guarded);\n }\n if (HasArrayKeywords(schema)) {\n const constraints = [];\n if (IsAdditionalItems(schema))\n constraints.push(BuildAdditionalItems(stack, context2, schema, value));\n if (IsContains(schema))\n constraints.push(BuildContains(stack, context2, schema, value));\n if (IsItems(schema))\n constraints.push(BuildItems(stack, context2, schema, value));\n if (IsMaxContains(schema))\n constraints.push(BuildMaxContains(stack, context2, schema, value));\n if (IsMaxItems(schema))\n constraints.push(BuildMaxItems(stack, context2, schema, value));\n if (IsMinContains(schema))\n constraints.push(BuildMinContains(stack, context2, schema, value));\n if (IsMinItems(schema))\n constraints.push(BuildMinItems(stack, context2, schema, value));\n if (IsPrefixItems(schema))\n constraints.push(BuildPrefixItems(stack, context2, schema, value));\n if (IsUniqueItems(schema))\n constraints.push(BuildUniqueItems(stack, context2, schema, value));\n const reduced = emit_exports.ReduceAnd(constraints);\n const guarded = emit_exports.Or(emit_exports.Not(emit_exports.IsArray(value)), reduced);\n conditions.push(HasArrayType(schema) ? reduced : guarded);\n }\n if (HasStringKeywords(schema)) {\n const constraints = [];\n if (IsMaxLength4(schema))\n constraints.push(BuildMaxLength(stack, context2, schema, value));\n if (IsMinLength4(schema))\n constraints.push(BuildMinLength(stack, context2, schema, value));\n if (IsFormat(schema))\n constraints.push(BuildFormat(stack, context2, schema, value));\n if (IsPattern(schema))\n constraints.push(BuildPattern(stack, context2, schema, value));\n const reduced = emit_exports.ReduceAnd(constraints);\n const guarded = emit_exports.Or(emit_exports.Not(emit_exports.IsString(value)), reduced);\n conditions.push(HasStringType(schema) ? reduced : guarded);\n }\n if (HasNumberKeywords(schema)) {\n const constraints = [];\n if (IsExclusiveMaximum(schema))\n constraints.push(BuildExclusiveMaximum(stack, context2, schema, value));\n if (IsExclusiveMinimum(schema))\n constraints.push(BuildExclusiveMinimum(stack, context2, schema, value));\n if (IsMaximum(schema))\n constraints.push(BuildMaximum(stack, context2, schema, value));\n if (IsMinimum(schema))\n constraints.push(BuildMinimum(stack, context2, schema, value));\n if (IsMultipleOf2(schema))\n constraints.push(BuildMultipleOf(stack, context2, schema, value));\n const reduced = emit_exports.ReduceAnd(constraints);\n const guarded = emit_exports.Or(emit_exports.Not(emit_exports.Or(emit_exports.IsNumber(value), emit_exports.IsBigInt(value))), reduced);\n conditions.push(HasNumberType(schema) ? reduced : guarded);\n }\n if (IsRef(schema))\n conditions.push(BuildRef(stack, context2, schema, value));\n if (IsRecursiveRef(schema))\n conditions.push(BuildRecursiveRef(stack, context2, schema, value));\n if (IsDynamicRef(schema))\n conditions.push(BuildDynamicRef(stack, context2, schema, value));\n if (IsConst(schema))\n conditions.push(BuildConst(stack, context2, schema, value));\n if (IsEnum(schema))\n conditions.push(BuildEnum(stack, context2, schema, value));\n if (IsIf(schema))\n conditions.push(BuildIf(stack, context2, schema, value));\n if (IsNot(schema))\n conditions.push(BuildNot(stack, context2, schema, value));\n if (IsAllOf(schema))\n conditions.push(BuildAllOf(stack, context2, schema, value));\n if (IsAnyOf(schema))\n conditions.push(BuildAnyOf(stack, context2, schema, value));\n if (IsOneOf(schema))\n conditions.push(BuildOneOf(stack, context2, schema, value));\n if (IsUnevaluatedItems(schema))\n conditions.push(emit_exports.Or(emit_exports.Not(emit_exports.IsArray(value)), BuildUnevaluatedItems(stack, context2, schema, value)));\n if (IsUnevaluatedProperties(schema))\n conditions.push(emit_exports.Or(emit_exports.Not(emit_exports.IsObject(value)), BuildUnevaluatedProperties(stack, context2, schema, value)));\n if (IsRefine(schema))\n conditions.push(BuildRefine(stack, context2, schema, value));\n const result = emit_exports.ReduceAnd(conditions);\n stack.Pop(schema);\n return result;\n }\n function CheckSchemaPushStack(stack, context2, schema, value) {\n return context2.Push() && CheckSchema(stack, context2, schema, value) && context2.Pop();\n }\n function CheckSchema(stack, context2, schema, value) {\n stack.Push(schema);\n const result = IsSchemaBoolean(schema) ? CheckSchemaBoolean(stack, context2, schema, value) : (!IsType(schema) || CheckType(stack, context2, schema, value)) && (!(guard_exports.IsObject(value) && !guard_exports.IsArray(value)) || (!IsRequired(schema) || CheckRequired(stack, context2, schema, value)) && (!IsAdditionalProperties(schema) || CheckAdditionalProperties(stack, context2, schema, value)) && (!IsDependencies(schema) || CheckDependencies(stack, context2, schema, value)) && (!IsDependentRequired(schema) || CheckDependentRequired(stack, context2, schema, value)) && (!IsDependentSchemas(schema) || CheckDependentSchemas(stack, context2, schema, value)) && (!IsPatternProperties(schema) || CheckPatternProperties(stack, context2, schema, value)) && (!IsProperties(schema) || CheckProperties(stack, context2, schema, value)) && (!IsPropertyNames(schema) || CheckPropertyNames(stack, context2, schema, value)) && (!IsMinProperties(schema) || CheckMinProperties(stack, context2, schema, value)) && (!IsMaxProperties(schema) || CheckMaxProperties(stack, context2, schema, value))) && (!guard_exports.IsArray(value) || (!IsAdditionalItems(schema) || CheckAdditionalItems(stack, context2, schema, value)) && (!IsContains(schema) || CheckContains(stack, context2, schema, value)) && (!IsItems(schema) || CheckItems(stack, context2, schema, value)) && (!IsMaxContains(schema) || CheckMaxContains(stack, context2, schema, value)) && (!IsMaxItems(schema) || CheckMaxItems(stack, context2, schema, value)) && (!IsMinContains(schema) || CheckMinContains(stack, context2, schema, value)) && (!IsMinItems(schema) || CheckMinItems(stack, context2, schema, value)) && (!IsPrefixItems(schema) || CheckPrefixItems(stack, context2, schema, value)) && (!IsUniqueItems(schema) || CheckUniqueItems(stack, context2, schema, value))) && (!guard_exports.IsString(value) || (!IsMaxLength4(schema) || CheckMaxLength(stack, context2, schema, value)) && (!IsMinLength4(schema) || CheckMinLength(stack, context2, schema, value)) && (!IsFormat(schema) || CheckFormat(stack, context2, schema, value)) && (!IsPattern(schema) || CheckPattern(stack, context2, schema, value))) && (!(guard_exports.IsNumber(value) || guard_exports.IsBigInt(value)) || (!IsExclusiveMaximum(schema) || CheckExclusiveMaximum(stack, context2, schema, value)) && (!IsExclusiveMinimum(schema) || CheckExclusiveMinimum(stack, context2, schema, value)) && (!IsMaximum(schema) || CheckMaximum(stack, context2, schema, value)) && (!IsMinimum(schema) || CheckMinimum(stack, context2, schema, value)) && (!IsMultipleOf2(schema) || CheckMultipleOf(stack, context2, schema, value))) && (!IsRef(schema) || CheckRef(stack, context2, schema, value)) && (!IsRecursiveRef(schema) || CheckRecursiveRef(stack, context2, schema, value)) && (!IsDynamicRef(schema) || CheckDynamicRef(stack, context2, schema, value)) && (!IsConst(schema) || CheckConst(stack, context2, schema, value)) && (!IsEnum(schema) || CheckEnum(stack, context2, schema, value)) && (!IsIf(schema) || CheckIf(stack, context2, schema, value)) && (!IsNot(schema) || CheckNot(stack, context2, schema, value)) && (!IsAllOf(schema) || CheckAllOf(stack, context2, schema, value)) && (!IsAnyOf(schema) || CheckAnyOf(stack, context2, schema, value)) && (!IsOneOf(schema) || CheckOneOf(stack, context2, schema, value)) && (!IsUnevaluatedItems(schema) || (!guard_exports.IsArray(value) || CheckUnevaluatedItems(stack, context2, schema, value))) && (!IsUnevaluatedProperties(schema) || (!guard_exports.IsObject(value) || CheckUnevaluatedProperties(stack, context2, schema, value))) && (!IsRefine(schema) || CheckRefine(stack, context2, schema, value));\n stack.Pop(schema);\n return result;\n }\n function ErrorSchemaPushStack(stack, context2, schemaPath, instancePath, schema, value) {\n return context2.Push() && ErrorSchema(stack, context2, schemaPath, instancePath, schema, value) && context2.Pop();\n }\n function ErrorSchema(stack, context2, schemaPath, instancePath, schema, value) {\n if (context2.AtCapacity())\n return false;\n stack.Push(schema);\n const result = IsSchemaBoolean(schema) ? ErrorSchemaBoolean(stack, context2, schemaPath, instancePath, schema, value) : !!(+(!IsType(schema) || ErrorType(stack, context2, schemaPath, instancePath, schema, value)) & +(!(guard_exports.IsObject(value) && !guard_exports.IsArray(value)) || !!(+(!IsRequired(schema) || ErrorRequired(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsAdditionalProperties(schema) || ErrorAdditionalProperties(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsDependencies(schema) || ErrorDependencies(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsDependentRequired(schema) || ErrorDependentRequired(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsDependentSchemas(schema) || ErrorDependentSchemas(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsPatternProperties(schema) || ErrorPatternProperties(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsProperties(schema) || ErrorProperties(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsPropertyNames(schema) || ErrorPropertyNames(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsMinProperties(schema) || ErrorMinProperties(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsMaxProperties(schema) || ErrorMaxProperties(stack, context2, schemaPath, instancePath, schema, value)))) & +(!guard_exports.IsArray(value) || !!(+(!IsAdditionalItems(schema) || ErrorAdditionalItems(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsContains(schema) || ErrorContains(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsItems(schema) || ErrorItems(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsMaxContains(schema) || ErrorMaxContains(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsMaxItems(schema) || ErrorMaxItems(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsMinContains(schema) || ErrorMinContains(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsMinItems(schema) || ErrorMinItems(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsPrefixItems(schema) || ErrorPrefixItems(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsUniqueItems(schema) || ErrorUniqueItems(stack, context2, schemaPath, instancePath, schema, value)))) & +(!guard_exports.IsString(value) || !!(+(!IsMaxLength4(schema) || ErrorMaxLength(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsMinLength4(schema) || ErrorMinLength(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsFormat(schema) || ErrorFormat(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsPattern(schema) || ErrorPattern(stack, context2, schemaPath, instancePath, schema, value)))) & +(!(guard_exports.IsNumber(value) || guard_exports.IsBigInt(value)) || !!(+(!IsExclusiveMaximum(schema) || ErrorExclusiveMaximum(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsExclusiveMinimum(schema) || ErrorExclusiveMinimum(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsMaximum(schema) || ErrorMaximum(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsMinimum(schema) || ErrorMinimum(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsMultipleOf2(schema) || ErrorMultipleOf(stack, context2, schemaPath, instancePath, schema, value)))) & +(!IsRef(schema) || ErrorRef(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsRecursiveRef(schema) || ErrorRecursiveRef(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsDynamicRef(schema) || ErrorDynamicRef(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsConst(schema) || ErrorConst(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsEnum(schema) || ErrorEnum(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsIf(schema) || ErrorIf(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsNot(schema) || ErrorNot(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsAllOf(schema) || ErrorAllOf(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsAnyOf(schema) || ErrorAnyOf(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsOneOf(schema) || ErrorOneOf(stack, context2, schemaPath, instancePath, schema, value)) & +(!IsUnevaluatedItems(schema) || (!guard_exports.IsArray(value) || ErrorUnevaluatedItems(stack, context2, schemaPath, instancePath, schema, value))) & +(!IsUnevaluatedProperties(schema) || (!guard_exports.IsObject(value) || ErrorUnevaluatedProperties(stack, context2, schemaPath, instancePath, schema, value)))) && (!IsRefine(schema) || ErrorRefine(stack, context2, schemaPath, instancePath, schema, value));\n stack.Pop(schema);\n return result;\n }\n\n // node_modules/typebox/build/schema/engine/_functions.mjs\n var index2 = [0];\n var names2 = /* @__PURE__ */ new Map();\n var funcs = /* @__PURE__ */ new Map();\n function NextName() {\n return `${index2[0]++}`;\n }\n function CreateName(schema, href) {\n if (!names2.has(schema))\n names2.set(schema, /* @__PURE__ */ new Map());\n const hrefs = names2.get(schema);\n if (hrefs.has(href))\n return hrefs.get(href);\n const name = NextName();\n hrefs.set(href, name);\n return name;\n }\n function CreateCallExpression(context2, _schema, name, value) {\n return context2.UseUnevaluated() ? emit_exports.Call(`check_${name}`, [\"context\", value]) : emit_exports.Call(`check_${name}`, [value]);\n }\n function CreateFunctionExpression(stack, context2, schema, name) {\n const expression = BuildSchema(stack, context2, schema, \"value\");\n return context2.UseUnevaluated() ? emit_exports.ConstDeclaration(`check_${name}`, emit_exports.ArrowFunction([\"context\", \"value\"], expression)) : emit_exports.ConstDeclaration(`check_${name}`, emit_exports.ArrowFunction([\"value\"], expression));\n }\n function ResetFunctions() {\n index2[0] = 0;\n names2.clear();\n funcs.clear();\n }\n function GetFunctions() {\n return [...funcs.values()];\n }\n function CreateFunction(stack, context2, schema, value) {\n const name = CreateName(schema, stack.LexicalBaseURL());\n const call = CreateCallExpression(context2, schema, name, value);\n if (funcs.has(name))\n return call;\n funcs.set(name, \"\");\n funcs.set(name, CreateFunctionExpression(stack, context2, schema, name));\n return call;\n }\n\n // node_modules/typebox/build/schema/resolve/resolve.mjs\n var resolve_exports = {};\n __export(resolve_exports, {\n Base: () => Base,\n DefaultBase: () => DefaultBase,\n DynamicRef: () => DynamicRef,\n Ref: () => Ref,\n ResolveDynamicRef: () => ResolveDynamicRef,\n ResolveRecursiveRef: () => ResolveRecursiveRef,\n ResolveRef: () => ResolveRef,\n Resource: () => Resource\n });\n\n // node_modules/typebox/build/schema/pointer/pointer.mjs\n var pointer_exports = {};\n __export(pointer_exports, {\n Delete: () => Delete,\n Get: () => Get3,\n Has: () => Has2,\n Indices: () => Indices,\n Set: () => Set4\n });\n function AssertNotRoot(indices) {\n if (indices.length === 0)\n throw Error(\"Cannot set root\");\n }\n function AssertCanSet(value) {\n if (!guard_exports.IsObject(value))\n throw Error(\"Cannot set value\");\n }\n function AssertIndex(index3) {\n if (guard_exports.IsUnsafePropertyKey(index3))\n throw Error(\"Pointer contains unsafe property key\");\n }\n function AssertIndices(indices) {\n for (const index3 of indices)\n AssertIndex(index3);\n }\n function IsNumericIndex(index3) {\n return /^(0|[1-9]\\d*)$/.test(index3);\n }\n function TakeIndexRight(indices) {\n return [\n indices.slice(0, indices.length - 1),\n indices.slice(indices.length - 1)[0]\n ];\n }\n function HasIndex(index3, value) {\n return guard_exports.IsObject(value) && guard_exports.HasPropertyKey(value, index3);\n }\n function GetIndex(index3, value) {\n return guard_exports.IsObject(value) && !guard_exports.IsUnsafePropertyKey(index3) ? value[index3] : void 0;\n }\n function GetIndices(indices, value) {\n return indices.reduce((value2, index3) => GetIndex(index3, value2), value);\n }\n function Indices(pointer) {\n if (guard_exports.IsEqual(pointer.length, 0))\n return [];\n const indices = pointer.split(\"/\").map((index3) => index3.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n return indices.length > 0 && indices[0] === \"\" ? indices.slice(1) : indices;\n }\n function Has2(value, pointer) {\n let current = value;\n return Indices(pointer).every((index3) => {\n if (!HasIndex(index3, current))\n return false;\n current = current[index3];\n return true;\n });\n }\n function Get3(value, pointer) {\n const indices = Indices(pointer);\n return GetIndices(indices, value);\n }\n function Set4(value, pointer, next) {\n const indices = Indices(pointer);\n AssertNotRoot(indices);\n AssertIndices(indices);\n const [head, index3] = TakeIndexRight(indices);\n const parent = GetIndices(head, value);\n AssertCanSet(parent);\n parent[index3] = next;\n return value;\n }\n function Delete(value, pointer) {\n const indices = Indices(pointer);\n AssertNotRoot(indices);\n AssertIndices(indices);\n const [head, index3] = TakeIndexRight(indices);\n const parent = GetIndices(head, value);\n AssertCanSet(parent);\n if (guard_exports.IsArray(parent) && IsNumericIndex(index3)) {\n parent.splice(+index3, 1);\n } else {\n delete parent[index3];\n }\n return value;\n }\n\n // node_modules/typebox/build/schema/resolve/resolve.mjs\n var DefaultBase = \"https://json-schema.org\";\n function FindDynamicAnchor(schema, name) {\n if (guard_exports.IsObject(schema) && IsDynamicAnchor(schema) && guard_exports.IsEqual(schema.$dynamicAnchor, name)) {\n return schema;\n }\n if (guard_exports.IsObject(schema)) {\n for (const key of guard_exports.Keys(schema)) {\n const result = FindDynamicAnchor(schema[key], name);\n if (result)\n return result;\n }\n }\n return void 0;\n }\n function FindBase(schema, base, target) {\n if (guard_exports.IsEqual(schema, target))\n return base.href;\n const nextBase = IsSchemaObject(schema) && IsId(schema) ? new URL(schema.$id, base.href) : base;\n if (guard_exports.IsArray(schema)) {\n for (const item of schema) {\n const result = FindBase(item, nextBase, target);\n if (!guard_exports.IsUndefined(result))\n return result;\n }\n } else if (guard_exports.IsObject(schema)) {\n for (const key of guard_exports.Keys(schema)) {\n const result = FindBase(schema[key], nextBase, target);\n if (!guard_exports.IsUndefined(result))\n return result;\n }\n }\n return void 0;\n }\n function MatchId(schema, base, ref) {\n if (guard_exports.IsEqual(schema.$id, ref.hash))\n return schema;\n const absoluteRef = new URL(ref.href, base.href);\n if (guard_exports.IsEqual(base.pathname, absoluteRef.pathname))\n return ref.hash.startsWith(\"#\") ? MatchHash(schema, ref) : schema;\n return void 0;\n }\n function MatchAnchor(schema, base, ref) {\n const absoluteAnchor = new URL(`#${schema.$anchor}`, base.href);\n const absoluteRef = new URL(ref.href, base.href);\n return guard_exports.IsEqual(absoluteAnchor.href, absoluteRef.href) ? schema : void 0;\n }\n function MatchDynamicAnchor(schema, base, ref) {\n const absoluteAnchor = new URL(`#${schema.$dynamicAnchor}`, base.href);\n const absoluteRef = new URL(ref.href, base.href);\n const isMatch = guard_exports.IsEqual(absoluteAnchor.href, absoluteRef.href);\n return isMatch ? schema : void 0;\n }\n function MatchHash(schema, ref) {\n if (ref.href.endsWith(\"#\"))\n return schema;\n if (!ref.hash.startsWith(\"#\"))\n return void 0;\n const fragment = decodeURIComponent(ref.hash.slice(1));\n if (!fragment.startsWith(\"/\"))\n return void 0;\n const result = pointer_exports.Get(schema, fragment);\n return result;\n }\n function Match2(schema, base, ref) {\n if (IsId(schema)) {\n const result = MatchId(schema, base, ref);\n if (!guard_exports.IsUndefined(result))\n return result;\n }\n if (IsAnchor(schema)) {\n const result = MatchAnchor(schema, base, ref);\n if (!guard_exports.IsUndefined(result))\n return result;\n }\n if (IsDynamicAnchor(schema)) {\n const result = MatchDynamicAnchor(schema, base, ref);\n if (!guard_exports.IsUndefined(result))\n return result;\n }\n return MatchHash(schema, ref);\n }\n function FromArray2(schema, base, ref) {\n return schema.reduce((result, item) => {\n const match = FromValue2(item, base, ref);\n return !guard_exports.IsUndefined(match) ? match : result;\n }, void 0);\n }\n function SkipProperty(key) {\n return guard_exports.IsEqual(key, \"const\") || guard_exports.IsEqual(key, \"enum\");\n }\n function FromObject2(schema, base, ref) {\n return guard_exports.Keys(schema).reduce((result, key) => {\n if (SkipProperty(key))\n return result;\n const match = FromValue2(schema[key], base, ref);\n return !guard_exports.IsUndefined(match) ? match : result;\n }, void 0);\n }\n function FromValue2(schema, base, ref) {\n const nextBase = IsSchemaObject(schema) && IsId(schema) ? new URL(schema.$id, base.href) : base;\n if (IsSchemaObject(schema)) {\n const result = Match2(schema, nextBase, ref);\n if (!guard_exports.IsUndefined(result))\n return result;\n }\n if (guard_exports.IsArray(schema))\n return FromArray2(schema, nextBase, ref);\n if (guard_exports.IsObject(schema))\n return FromObject2(schema, nextBase, ref);\n return void 0;\n }\n function Base(schema, base, target) {\n return FindBase(schema, new URL(base || \".\", DefaultBase), target);\n }\n function Resource(context2, schema, base, ref) {\n const result = Ref(context2, schema, base, ref, false);\n return IsSchemaObject(result) && IsId(result) ? result : void 0;\n }\n function CanonicalHref(url) {\n return url.href.split(\"#\")[0];\n }\n function RefContext(context2, ref) {\n return guard_exports.HasPropertyKey(context2, ref) ? context2[ref] : void 0;\n }\n function RefLocal(schema, base, ref) {\n return FromValue2(schema, base, ref);\n }\n function RefRemote(context2, base, ref) {\n const canonicalHref = CanonicalHref(ref);\n if (guard_exports.IsEqual(canonicalHref, CanonicalHref(base)))\n return void 0;\n if (!guard_exports.HasPropertyKey(context2, canonicalHref))\n return void 0;\n const remoteSchema = context2[canonicalHref];\n const remoteBase = IsSchemaObject(remoteSchema) && IsId(remoteSchema) ? new URL(remoteSchema.$id, canonicalHref) : new URL(canonicalHref);\n const result = guard_exports.IsEqual(ref.hash, \"\") ? remoteSchema : FromValue2(remoteSchema, remoteBase, ref);\n return result;\n }\n function LegacyRetrievedResource(root2, lexicalSchema, referenceBase, ref, schema) {\n if (!ref.$ref.startsWith(\"#\"))\n return void 0;\n if (guard_exports.HasPropertyKey(root2, \"$schema\"))\n return void 0;\n const targetBase = Base(lexicalSchema, referenceBase, schema);\n if (guard_exports.IsUndefined(targetBase) || guard_exports.IsEqual(targetBase, referenceBase))\n return void 0;\n return { target: schema, base: targetBase, root: lexicalSchema };\n }\n function RemoteRetrievedResource(context2, canonical, schema) {\n const remoteRoot = context2[canonical];\n if (!IsSchemaObject(remoteRoot))\n return void 0;\n return { target: schema, base: canonical, root: remoteRoot };\n }\n function FindRetrievedResource(stackframe, ref, schema, canonical, isRemote) {\n const remote = isRemote ? RemoteRetrievedResource(stackframe.context, canonical, schema) : void 0;\n if (!guard_exports.IsUndefined(remote))\n return remote;\n return LegacyRetrievedResource(stackframe.root, stackframe.lexicalSchema, stackframe.referenceBase, ref, schema);\n }\n function FindResolvedResource(context2, root2, referenceBase, canonical, schema, ids) {\n if (IsId(schema))\n return void 0;\n const resource = Resource(context2, root2, referenceBase, canonical);\n if (!resource || ids.includes(resource))\n return void 0;\n return { target: schema, resource };\n }\n function Ref(remotes, schema, base, ref, applySchemaId = true) {\n const initialBase = new URL(base || \".\", DefaultBase);\n const resolvedBase = applySchemaId && IsId(schema) ? new URL(schema.$id, initialBase) : initialBase;\n const initialRef = new URL(ref, resolvedBase.href);\n return RefContext(remotes, ref) ?? RefLocal(schema, resolvedBase, initialRef) ?? RefRemote(remotes, resolvedBase, initialRef);\n }\n function DynamicRef(context2, root2, base, schema, dynamicRef, dynamicAnchors) {\n const initialBase = new URL(base || \".\", DefaultBase);\n const fragmentRoot = dynamicRef.$dynamicRef.startsWith(\"#\") ? schema : root2;\n const fragmentTarget = Ref(context2, fragmentRoot, base, dynamicRef.$dynamicRef, false);\n if (guard_exports.IsUndefined(fragmentTarget)) {\n const fragment2 = new URL(dynamicRef.$dynamicRef, initialBase).hash;\n if (!fragment2.startsWith(\"#/\") && fragment2.startsWith(\"#\")) {\n const name = decodeURIComponent(fragment2.slice(1));\n const anchorTarget2 = dynamicAnchors.find((anchor) => guard_exports.IsEqual(anchor.$dynamicAnchor, name)) ?? FindDynamicAnchor(root2, name);\n return anchorTarget2;\n }\n return void 0;\n }\n if (!IsSchemaObject(fragmentTarget) || !IsDynamicAnchor(fragmentTarget))\n return fragmentTarget;\n const fragment = new URL(dynamicRef.$dynamicRef, initialBase).hash;\n if (fragment.startsWith(\"#/\"))\n return fragmentTarget;\n const anchorTarget = dynamicAnchors.find((anchor) => guard_exports.IsEqual(anchor.$dynamicAnchor, fragmentTarget.$dynamicAnchor));\n return anchorTarget ?? fragmentTarget;\n }\n function ResolveRef(stackframe, ref) {\n const source = stackframe.inRetrievedFrame ? stackframe.lexicalSchema : stackframe.root;\n const refRoot = ref.$ref.startsWith(\"#\") ? stackframe.lexicalSchema : source;\n const schema = Ref(stackframe.context, refRoot, stackframe.referenceBase, ref.$ref, false);\n if (!schema || !IsSchemaObject(schema))\n return { schema };\n const canonical = new URL(ref.$ref, stackframe.referenceBase).href.split(\"#\")[0];\n const isRemote = !guard_exports.IsEqual(canonical, stackframe.resourceBase);\n const retrievedResource = FindRetrievedResource(stackframe, ref, schema, canonical, isRemote);\n const resolvedResource = isRemote ? FindResolvedResource(stackframe.context, stackframe.root, stackframe.referenceBase, canonical, schema, stackframe.ids) : void 0;\n return { schema, retrievedResource, resolvedResource };\n }\n function ResolveRecursiveRef(stackframe, recursiveRef) {\n const refRoot = IsRecursiveAnchorTrue(stackframe.lexicalSchema) ? stackframe.recursiveAnchors[0] : stackframe.lexicalSchema;\n return Ref(stackframe.context, refRoot, stackframe.lexicalBase, recursiveRef.$recursiveRef, false);\n }\n function ResolveDynamicRef(stackframe, dynamicRef) {\n return DynamicRef(stackframe.context, stackframe.root, stackframe.lexicalBase, stackframe.lexicalSchema, dynamicRef, stackframe.dynamicAnchors);\n }\n\n // node_modules/typebox/build/schema/engine/_stack.mjs\n var __classPrivateFieldGet = function(receiver, state2, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state2 === \"function\" ? receiver !== state2 || !f : !state2.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state2.get(receiver);\n };\n var _Stack_instances;\n var _Stack_StackFrame;\n var _Stack_ApplyRefResult;\n var _Stack_BuildBase;\n var _Stack_ResourceBaseURL;\n var _Stack_ReferenceBaseURL;\n var _Stack_LexicalSchema;\n var _Stack_RegisterResourceAnchorArray;\n var _Stack_UnregisterResourceAnchorArray;\n var _Stack_RegisterResourceAnchors;\n var _Stack_UnregisterResourceAnchors;\n var _Stack_RegisterResource;\n var _Stack_UnregisterResource;\n var _Stack_EnterResolvedResource;\n var _Stack_ExitResolvedResource;\n var Stack = class {\n constructor(context2, schema) {\n _Stack_instances.add(this);\n this.context = context2;\n this.schema = schema;\n this.ids = [];\n this.resourceIds = [];\n this.anchors = [];\n this.recursiveAnchors = [];\n this.dynamicAnchors = [];\n this.retrievedResources = /* @__PURE__ */ new Map();\n this.retrievedFrames = [];\n this.resolvedResources = /* @__PURE__ */ new Map();\n this.pendingResource = true;\n }\n // ----------------------------------------------------------------\n // LexicalBaseURL\n // ----------------------------------------------------------------\n LexicalBaseURL() {\n return __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_BuildBase).call(this, this.ids);\n }\n // ----------------------------------------------------------------\n // Push\n // ----------------------------------------------------------------\n Push(schema) {\n if (!IsSchemaObject(schema))\n return;\n if (IsId(schema))\n __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_RegisterResource).call(this, schema);\n if (IsAnchor(schema))\n this.anchors.push(schema);\n if (IsRecursiveAnchorTrue(schema))\n this.recursiveAnchors.push(schema);\n if (IsDynamicAnchor(schema))\n this.dynamicAnchors.push(schema);\n const retrievedResource = this.retrievedResources.get(schema);\n if (retrievedResource) {\n this.retrievedFrames.push({\n schema: retrievedResource.root,\n base: retrievedResource.base,\n idDepth: this.ids.length,\n resourceDepth: this.resourceIds.length\n });\n }\n }\n // ----------------------------------------------------------------\n // Pop\n // ----------------------------------------------------------------\n Pop(schema) {\n if (!IsSchemaObject(schema))\n return;\n if (IsId(schema))\n __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_UnregisterResource).call(this, schema);\n if (IsAnchor(schema))\n this.anchors.pop();\n if (IsRecursiveAnchorTrue(schema))\n this.recursiveAnchors.pop();\n if (IsDynamicAnchor(schema))\n this.dynamicAnchors.pop();\n if (this.retrievedResources.has(schema))\n this.retrievedFrames.pop();\n __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_ExitResolvedResource).call(this, schema);\n }\n // ----------------------------------------------------------------\n // Ref\n // ----------------------------------------------------------------\n Ref(ref) {\n const result = resolve_exports.ResolveRef(__classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_StackFrame).call(this), ref);\n __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_ApplyRefResult).call(this, result);\n return result.schema;\n }\n // ----------------------------------------------------------------\n // RecursiveRef\n // ----------------------------------------------------------------\n RecursiveRef(recursiveRef) {\n const result = resolve_exports.ResolveRecursiveRef(__classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_StackFrame).call(this), recursiveRef);\n if (result)\n this.pendingResource = true;\n return result;\n }\n // ----------------------------------------------------------------\n // DynamicRef\n // ----------------------------------------------------------------\n DynamicRef(dynamicRef) {\n const result = resolve_exports.ResolveDynamicRef(__classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_StackFrame).call(this), dynamicRef);\n if (result)\n this.pendingResource = true;\n return result;\n }\n };\n _Stack_instances = /* @__PURE__ */ new WeakSet(), _Stack_StackFrame = function _Stack_StackFrame2() {\n return {\n context: this.context,\n root: this.schema,\n ids: this.ids,\n lexicalSchema: __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_LexicalSchema).call(this),\n lexicalBase: this.LexicalBaseURL(),\n referenceBase: __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_ReferenceBaseURL).call(this),\n resourceBase: __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_ResourceBaseURL).call(this),\n recursiveAnchors: this.recursiveAnchors,\n dynamicAnchors: this.dynamicAnchors,\n inRetrievedFrame: this.retrievedFrames.length > 0\n };\n }, _Stack_ApplyRefResult = function _Stack_ApplyRefResult2(result) {\n if (!guard_exports.IsUndefined(result.schema))\n this.pendingResource = true;\n if (!guard_exports.IsUndefined(result.resolvedResource)) {\n __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_EnterResolvedResource).call(this, result.resolvedResource.target, result.resolvedResource.resource);\n }\n if (!guard_exports.IsUndefined(result.retrievedResource)) {\n this.retrievedResources.set(result.retrievedResource.target, {\n base: result.retrievedResource.base,\n root: result.retrievedResource.root\n });\n }\n }, _Stack_BuildBase = function _Stack_BuildBase2(stack) {\n const frame = this.retrievedFrames[this.retrievedFrames.length - 1];\n const base = frame ? new URL(frame.base) : new URL(resolve_exports.DefaultBase);\n const scoped = frame ? stack.slice(frame.idDepth) : stack;\n return scoped.reduce((result, schema) => new URL(schema.$id, result), base).href;\n }, _Stack_ResourceBaseURL = function _Stack_ResourceBaseURL2() {\n const frame = this.retrievedFrames[this.retrievedFrames.length - 1];\n if (!frame)\n return __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_BuildBase).call(this, this.resourceIds);\n return this.resourceIds.slice(frame.resourceDepth).reduce((result, schema) => new URL(schema.$id, result), new URL(frame.base)).href;\n }, _Stack_ReferenceBaseURL = function _Stack_ReferenceBaseURL2() {\n if (this.retrievedFrames.length > 0)\n return __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_ResourceBaseURL).call(this);\n const lexical = this.ids[this.ids.length - 1];\n if (lexical && !/^[A-Za-z][A-Za-z0-9+.-]*:/.test(lexical.$id))\n return this.LexicalBaseURL();\n return __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_ResourceBaseURL).call(this);\n }, _Stack_LexicalSchema = function _Stack_LexicalSchema2() {\n const frame = this.retrievedFrames[this.retrievedFrames.length - 1];\n if (frame)\n return this.ids.length > frame.idDepth ? this.ids[this.ids.length - 1] : frame.schema;\n return this.ids.length > 0 ? this.ids[this.ids.length - 1] : this.schema;\n }, _Stack_RegisterResourceAnchorArray = function _Stack_RegisterResourceAnchorArray2(schema) {\n schema.forEach((schema2) => __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_RegisterResourceAnchors).call(this, schema2, false));\n }, _Stack_UnregisterResourceAnchorArray = function _Stack_UnregisterResourceAnchorArray2(schema) {\n schema.forEach((schema2) => __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_UnregisterResourceAnchors).call(this, schema2, false));\n }, _Stack_RegisterResourceAnchors = function _Stack_RegisterResourceAnchors2(schema, isRoot = true) {\n if (IsSchemaBoolean(schema))\n return;\n if (guard_exports.IsArray(schema))\n return __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_RegisterResourceAnchorArray).call(this, schema);\n if (!IsSchemaObject(schema))\n return;\n const current = schema;\n if (!isRoot && IsId(current))\n return;\n if (!isRoot && IsDynamicAnchor(current))\n this.dynamicAnchors.push(current);\n for (const key of guard_exports.Keys(current))\n __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_RegisterResourceAnchors2).call(this, current[key], false);\n }, _Stack_UnregisterResourceAnchors = function _Stack_UnregisterResourceAnchors2(schema, isRoot = true) {\n if (IsSchemaBoolean(schema))\n return;\n if (guard_exports.IsArray(schema))\n return __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_UnregisterResourceAnchorArray).call(this, schema);\n if (!IsSchemaObject(schema))\n return;\n const current = schema;\n if (!isRoot && IsId(current))\n return;\n if (!isRoot && IsDynamicAnchor(current))\n this.dynamicAnchors.pop();\n for (const key of guard_exports.Keys(current))\n __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_UnregisterResourceAnchors2).call(this, current[key], false);\n }, _Stack_RegisterResource = function _Stack_RegisterResource2(schema) {\n this.ids.push(schema);\n const isResource = this.pendingResource;\n this.pendingResource = false;\n if (isResource)\n this.resourceIds.push(schema);\n __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_RegisterResourceAnchors).call(this, schema, true);\n }, _Stack_UnregisterResource = function _Stack_UnregisterResource2(schema) {\n this.ids.pop();\n const isResource = this.resourceIds.length > 0 && guard_exports.IsEqual(this.resourceIds[this.resourceIds.length - 1], schema);\n if (isResource)\n this.resourceIds.pop();\n __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_UnregisterResourceAnchors).call(this, schema, true);\n }, _Stack_EnterResolvedResource = function _Stack_EnterResolvedResource2(target, resource) {\n __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_RegisterResource).call(this, resource);\n this.resolvedResources.set(target, resource);\n }, _Stack_ExitResolvedResource = function _Stack_ExitResolvedResource2(target) {\n if (!this.resolvedResources.has(target))\n return;\n const resource = this.resolvedResources.get(target);\n __classPrivateFieldGet(this, _Stack_instances, \"m\", _Stack_UnregisterResource).call(this, resource);\n this.resolvedResources.delete(target);\n };\n\n // node_modules/typebox/build/system/environment/environment.mjs\n var environment_exports = {};\n __export(environment_exports, {\n CanEvaluate: () => CanEvaluate,\n Evaluate: () => Evaluate\n });\n\n // node_modules/typebox/build/system/environment/evaluate.mjs\n var supported = void 0;\n function TryEvaluate() {\n try {\n Evaluate(\"null\")();\n return true;\n } catch {\n return false;\n }\n }\n function CanEvaluate() {\n if (guard_exports.IsUndefined(supported))\n supported = TryEvaluate();\n return supported && settings_exports.Get().useAcceleration;\n }\n function Evaluate(...args) {\n return new globalThis.Function(...args);\n }\n\n // node_modules/typebox/build/system/locale/en_US.mjs\n function en_US(error) {\n switch (error.keyword) {\n case \"additionalProperties\":\n return \"must not have additional properties\";\n case \"anyOf\":\n return \"must match a schema in anyOf\";\n case \"boolean\":\n return \"schema is false\";\n case \"const\":\n return \"must be equal to constant\";\n case \"contains\":\n return \"must contain at least 1 valid item\";\n case \"dependencies\":\n return `must have properties ${error.params.dependencies.join(\", \")} when property ${error.params.property} is present`;\n case \"dependentRequired\":\n return `must have properties ${error.params.dependencies.join(\", \")} when property ${error.params.property} is present`;\n case \"enum\":\n return \"must be equal to one of the allowed values\";\n case \"exclusiveMaximum\":\n return `must be ${error.params.comparison} ${error.params.limit}`;\n case \"exclusiveMinimum\":\n return `must be ${error.params.comparison} ${error.params.limit}`;\n case \"format\":\n return `must match format \"${error.params.format}\"`;\n case \"if\":\n return `must match \"${error.params.failingKeyword}\" schema`;\n case \"maxItems\":\n return `must not have more than ${error.params.limit} items`;\n case \"maxLength\":\n return `must not have more than ${error.params.limit} characters`;\n case \"maxProperties\":\n return `must not have more than ${error.params.limit} properties`;\n case \"maximum\":\n return `must be ${error.params.comparison} ${error.params.limit}`;\n case \"minItems\":\n return `must not have fewer than ${error.params.limit} items`;\n case \"minLength\":\n return `must not have fewer than ${error.params.limit} characters`;\n case \"minProperties\":\n return `must not have fewer than ${error.params.limit} properties`;\n case \"minimum\":\n return `must be ${error.params.comparison} ${error.params.limit}`;\n case \"multipleOf\":\n return `must be multiple of ${error.params.multipleOf}`;\n case \"not\":\n return \"must not be valid\";\n case \"oneOf\":\n return \"must match exactly one schema in oneOf\";\n case \"pattern\":\n return `must match pattern \"${error.params.pattern}\"`;\n case \"propertyNames\":\n return `property names ${error.params.propertyNames.join(\", \")} are invalid`;\n case \"required\":\n return `must have required properties ${error.params.requiredProperties.join(\", \")}`;\n case \"type\":\n return typeof error.params.type === \"string\" ? `must be ${error.params.type}` : `must be either ${error.params.type.join(\" or \")}`;\n case \"unevaluatedItems\":\n return \"must not have unevaluated items\";\n case \"unevaluatedProperties\":\n return \"must not have unevaluated properties\";\n case \"uniqueItems\":\n return `must not have duplicate items`;\n case \"~refine\":\n return error.params.message;\n // deno-coverage-ignore - unreachable\n default:\n return \"an unknown validation error occurred\";\n }\n }\n\n // node_modules/typebox/build/system/locale/_config.mjs\n var locale = en_US;\n function Get4() {\n return locale;\n }\n\n // node_modules/typebox/build/system/memory/memory.mjs\n var memory_exports = {};\n __export(memory_exports, {\n Assign: () => Assign,\n Clone: () => Clone,\n Create: () => Create,\n Discard: () => Discard,\n Metrics: () => Metrics,\n Update: () => Update\n });\n\n // node_modules/typebox/build/system/memory/metrics.mjs\n var Metrics = {\n assign: 0,\n create: 0,\n clone: 0,\n discard: 0,\n update: 0\n };\n\n // node_modules/typebox/build/system/memory/freeze.mjs\n function Freeze(value) {\n return settings_exports.Get().immutableTypes ? Object.freeze(value) : value;\n }\n\n // node_modules/typebox/build/system/memory/assign.mjs\n function Assign(left, right) {\n Metrics.assign += 1;\n return Freeze({ ...left, ...right });\n }\n\n // node_modules/typebox/build/system/memory/clone.mjs\n function FromClassInstance(value) {\n return value;\n }\n function IsSchemaObject2(value) {\n return guard_exports.HasPropertyKey(value, \"~kind\") || guard_exports.HasPropertyKey(value, \"~unsafe\");\n }\n function FromSchemaObject(value) {\n const result = {};\n for (const key of guard_exports.Keys(value)) {\n if (guard_exports.IsUnsafePropertyKey(key))\n continue;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n descriptor.value = FromValue3(descriptor.value);\n if (guard_exports.IsEqual(descriptor.enumerable, true)) {\n result[key] = descriptor.value;\n } else {\n Object.defineProperty(result, key, descriptor);\n }\n }\n return result;\n }\n function FromPlainObject(value) {\n const result = {};\n for (const key of guard_exports.Keys(value)) {\n if (guard_exports.IsUnsafePropertyKey(key))\n continue;\n result[key] = FromValue3(value[key]);\n }\n for (const key of guard_exports.Symbols(value)) {\n result[key] = FromValue3(value[key]);\n }\n return result;\n }\n function FromObject3(value) {\n return guard_exports.IsClassInstance(value) ? FromClassInstance(value) : IsSchemaObject2(value) ? FromSchemaObject(value) : FromPlainObject(value);\n }\n function FromArray3(value) {\n return value.map((element) => FromValue3(element));\n }\n function FromTypedArray(value) {\n return value.slice();\n }\n function FromRegExp2(value) {\n return new RegExp(value.source, value.flags);\n }\n function FromMap(value) {\n return new Map(FromValue3([...value.entries()]));\n }\n function FromSet(value) {\n return new Set(FromValue3([...value.values()]));\n }\n function FromValue3(value) {\n return globals_exports.IsTypeArray(value) ? FromTypedArray(value) : globals_exports.IsRegExp(value) ? FromRegExp2(value) : globals_exports.IsMap(value) ? FromMap(value) : globals_exports.IsSet(value) ? FromSet(value) : guard_exports.IsArray(value) ? FromArray3(value) : guard_exports.IsObject(value) ? FromObject3(value) : value;\n }\n function Clone(value) {\n Metrics.clone += 1;\n return FromValue3(value);\n }\n\n // node_modules/typebox/build/system/memory/create.mjs\n function MergeHidden(left, right) {\n for (const key of Object.keys(right)) {\n Object.defineProperty(left, key, {\n configurable: true,\n writable: true,\n enumerable: false,\n value: right[key]\n });\n }\n return left;\n }\n function Merge(left, right) {\n return { ...left, ...right };\n }\n function Create(hidden, enumerable, options = {}) {\n Metrics.create += 1;\n const withOptions = Merge(enumerable, options);\n const withHidden = settings_exports.Get().enumerableKind ? Merge(withOptions, hidden) : MergeHidden(withOptions, hidden);\n return Freeze(withHidden);\n }\n\n // node_modules/typebox/build/system/memory/discard.mjs\n function Discard(value, propertyKeys) {\n Metrics.discard += 1;\n const result = {};\n for (const key of guard_exports.Keys(value)) {\n if (propertyKeys.includes(key))\n continue;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n descriptor.value = Clone(descriptor.value);\n Object.defineProperty(result, key, descriptor);\n }\n return Freeze(result);\n }\n\n // node_modules/typebox/build/system/memory/update.mjs\n function Update(current, hidden, enumerable) {\n Metrics.update += 1;\n const settings2 = settings_exports.Get();\n const result = Clone(current);\n for (const key of Object.keys(hidden)) {\n Object.defineProperty(result, key, {\n configurable: true,\n writable: true,\n enumerable: settings2.enumerableKind,\n value: hidden[key]\n });\n }\n for (const key of Object.keys(enumerable)) {\n Object.defineProperty(result, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value: enumerable[key]\n });\n }\n return Freeze(result);\n }\n\n // node_modules/typebox/build/schema/build.mjs\n function CreateCode(build) {\n const functions = build.Functions().join(\";\\n\");\n const statements = build.UseUnevaluated() ? [\"const context = new CheckContext({}, {})\", `return ${build.Entry()}`] : [`return ${build.Entry()}`];\n return `${functions}; return (value) => { ${statements.join(\"; \")} }`;\n }\n function CreateEvaluatedCheck(build, code) {\n const factory = environment_exports.Evaluate(\"CheckContext\", \"Guard\", \"Format\", \"Hashing\", build.External().identifier, code);\n return factory(CheckContext, guard_exports, format_exports, hash_exports, build.External().variables);\n }\n function CreateDynamicCheck(build) {\n const stack = new Stack(build.Context(), build.Schema());\n const context2 = new CheckContext();\n return (value) => CheckSchema(stack, context2, build.Schema(), value);\n }\n function CreateCheck(build, code) {\n return environment_exports.CanEvaluate() ? CreateEvaluatedCheck(build, code) : CreateDynamicCheck(build);\n }\n var EvaluateResult = class {\n constructor(isAccelerated, code, check) {\n this.isAccelerated = isAccelerated;\n this.code = code;\n this.check = check;\n }\n IsAccelerated() {\n return this.isAccelerated;\n }\n Code() {\n return this.code;\n }\n Check(value) {\n return this.check(value);\n }\n };\n var BuildResult = class {\n constructor(context2, schema, external, functions, entry, useUnevaluated) {\n this.context = context2;\n this.schema = schema;\n this.external = external;\n this.functions = functions;\n this.entry = entry;\n this.useUnevaluated = useUnevaluated;\n }\n /** Returns the Context used for this build */\n Context() {\n return this.context;\n }\n /** Returns the Schema used for this build */\n Schema() {\n return this.schema;\n }\n /** Returns true if this build requires a Unevaluated context */\n UseUnevaluated() {\n return this.useUnevaluated;\n }\n /** Returns external variables */\n External() {\n return this.external;\n }\n /** Returns check functions */\n Functions() {\n return this.functions;\n }\n /** Return entry function call. */\n Entry() {\n return this.entry;\n }\n /** Evaluates the build into a validation function */\n Evaluate() {\n const code = CreateCode(this);\n const check = CreateCheck(this, code);\n return new EvaluateResult(environment_exports.CanEvaluate(), code, check);\n }\n };\n function Build(...args) {\n const [context2, schema] = arguments_exports.Match(args, {\n 2: (context3, schema2) => [context3, schema2],\n 1: (schema2) => [{}, schema2]\n });\n ResetExternal();\n ResetFunctions();\n const stack = new Stack(context2, schema);\n const build = new BuildContext(HasUnevaluated(context2, schema));\n const call = CreateFunction(stack, build, schema, \"value\");\n const functions = GetFunctions();\n const externals = GetExternal();\n return new BuildResult(context2, schema, externals, functions, call, build.UseUnevaluated());\n }\n\n // node_modules/typebox/build/schema/errors.mjs\n function Errors(...args) {\n const [context2, schema, value] = arguments_exports.Match(args, {\n 3: (context3, schema2, value2) => [context3, schema2, value2],\n 2: (schema2, value2) => [{}, schema2, value2]\n });\n const stack = new Stack(context2, schema);\n const errorContext = new ErrorContext();\n const result = ErrorSchema(stack, errorContext, \"#\", \"\", schema, value);\n const errors = errorContext.GetErrors();\n const locale2 = Get4();\n const localized = errors.map((error) => ({ ...error, message: locale2(error) }));\n return [result, localized];\n }\n\n // node_modules/typebox/build/schema/check.mjs\n function Check(...args) {\n const [context2, schema, value] = arguments_exports.Match(args, {\n 3: (context3, schema2, value2) => [context3, schema2, value2],\n 2: (schema2, value2) => [{}, schema2, value2]\n });\n const stack = new Stack(context2, schema);\n const checkContext = new CheckContext();\n return CheckSchema(stack, checkContext, schema, value);\n }\n\n // node_modules/typebox/build/value/check/check.mjs\n function Check2(...args) {\n const [context2, type, value] = arguments_exports.Match(args, {\n 3: (context3, type2, value2) => [context3, type2, value2],\n 2: (type2, value2) => [{}, type2, value2]\n });\n return Check(context2, type, value);\n }\n\n // node_modules/typebox/build/value/errors/errors.mjs\n function Errors2(...args) {\n const [context2, type, value] = arguments_exports.Match(args, {\n 3: (context3, type2, value2) => [context3, type2, value2],\n 2: (type2, value2) => [{}, type2, value2]\n });\n const [_, errors] = Errors(context2, type, value);\n return errors;\n }\n\n // node_modules/typebox/build/value/assert/assert.mjs\n var AssertError = class extends Error {\n constructor(source, value, errors) {\n super(source);\n Object.defineProperty(this, \"cause\", {\n value: { source, errors, value },\n writable: false,\n configurable: false,\n enumerable: false\n });\n }\n };\n function Assert(...args) {\n const [context2, type, value] = arguments_exports.Match(args, {\n 3: (context3, type2, value2) => [context3, type2, value2],\n 2: (type2, value2) => [{}, type2, value2]\n });\n const check = Check2(context2, type, value);\n if (!check)\n throw new AssertError(\"Assert\", value, Errors2(context2, type, value));\n }\n\n // node_modules/typebox/build/type/types/schema.mjs\n function IsKind(value, kind) {\n return guard_exports.IsObject(value) && guard_exports.HasPropertyKey(value, \"~kind\") && guard_exports.IsEqual(value[\"~kind\"], kind);\n }\n function IsSchema2(value) {\n return guard_exports.IsObject(value);\n }\n\n // node_modules/typebox/build/type/types/deferred.mjs\n function Deferred(action, parameters, options) {\n return memory_exports.Create({ \"~kind\": \"Deferred\" }, { type: \"deferred\", action, parameters, options }, {});\n }\n function IsDeferred(value) {\n return IsKind(value, \"Deferred\");\n }\n\n // node_modules/typebox/build/type/engine/readonly/instantiate_add.mjs\n function AddReadonlyOperation(type) {\n return memory_exports.Update(type, { \"~readonly\": true }, {});\n }\n function AddReadonlyAction(type, options) {\n const result = memory_exports.Update(AddReadonlyOperation(type), {}, options);\n return result;\n }\n function AddReadonlyInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return AddReadonlyAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/engine/optional/instantiate_add.mjs\n function AddOptionalOperation(type) {\n return memory_exports.Update(type, { \"~optional\": true }, {});\n }\n function AddOptionalAction(type, options) {\n const result = memory_exports.Update(AddOptionalOperation(type), {}, options);\n return result;\n }\n function AddOptionalInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return AddOptionalAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/types/array.mjs\n function _Array_(items, options) {\n return memory_exports.Create({ \"~kind\": \"Array\" }, { type: \"array\", items }, options);\n }\n function IsArray3(value) {\n return IsKind(value, \"Array\");\n }\n function ArrayOptions(type) {\n return memory_exports.Discard(type, [\"~kind\", \"type\", \"items\"]);\n }\n\n // node_modules/typebox/build/type/types/constructor.mjs\n function Constructor(parameters, instanceType, options = {}) {\n return memory_exports.Create({ \"~kind\": \"Constructor\" }, { type: \"constructor\", parameters, instanceType }, options);\n }\n function IsConstructor3(value) {\n return IsKind(value, \"Constructor\");\n }\n function ConstructorOptions(type) {\n return memory_exports.Discard(type, [\"~kind\", \"type\", \"parameters\", \"instanceType\"]);\n }\n\n // node_modules/typebox/build/type/types/function.mjs\n function _Function_(parameters, returnType, options = {}) {\n return memory_exports.Create({ [\"~kind\"]: \"Function\" }, { type: \"function\", parameters, returnType }, options);\n }\n function IsFunction3(value) {\n return IsKind(value, \"Function\");\n }\n function FunctionOptions(type) {\n return memory_exports.Discard(type, [\"~kind\", \"type\", \"parameters\", \"returnType\"]);\n }\n\n // node_modules/typebox/build/type/types/ref.mjs\n function Ref2(ref, options) {\n return memory_exports.Create({ [\"~kind\"]: \"Ref\" }, { $ref: ref }, options);\n }\n function IsRef2(value) {\n return IsKind(value, \"Ref\");\n }\n\n // node_modules/typebox/build/type/types/generic.mjs\n function Generic(parameters, expression) {\n return memory_exports.Create({ \"~kind\": \"Generic\" }, { type: \"generic\", parameters, expression });\n }\n function IsGeneric(value) {\n return IsKind(value, \"Generic\");\n }\n\n // node_modules/typebox/build/type/types/any.mjs\n function Any(options) {\n return memory_exports.Create({ [\"~kind\"]: \"Any\" }, {}, options);\n }\n function IsAny(value) {\n return IsKind(value, \"Any\");\n }\n\n // node_modules/typebox/build/type/types/never.mjs\n var NeverPattern = \"(?!)\";\n function Never(options) {\n return memory_exports.Create({ \"~kind\": \"Never\" }, { not: {} }, options);\n }\n function IsNever(value) {\n return IsKind(value, \"Never\");\n }\n\n // node_modules/typebox/build/type/action/_add_optional.mjs\n function AddOptionalDeferred(type, options = {}) {\n return Deferred(\"AddOptional\", [type], options);\n }\n function AddOptional(type, options = {}) {\n return AddOptionalAction(type, options);\n }\n\n // node_modules/typebox/build/type/types/_optional.mjs\n function Optional(type) {\n return AddOptional(type);\n }\n function IsOptional(value) {\n return IsSchema2(value) && guard_exports.HasPropertyKey(value, \"~optional\");\n }\n\n // node_modules/typebox/build/type/types/properties.mjs\n function RequiredArray(properties) {\n return guard_exports.Keys(properties).filter((key) => !IsOptional(properties[key]));\n }\n function PropertyKeys(properties) {\n return guard_exports.Keys(properties);\n }\n function PropertyValues(properties) {\n return guard_exports.Values(properties);\n }\n\n // node_modules/typebox/build/type/types/object.mjs\n function _Object_(properties, options = {}) {\n const requiredKeys = RequiredArray(properties);\n const required = requiredKeys.length > 0 ? { required: requiredKeys } : {};\n return memory_exports.Create({ \"~kind\": \"Object\" }, { type: \"object\", ...required, properties }, options);\n }\n function IsObject3(value) {\n return IsKind(value, \"Object\");\n }\n function ObjectOptions(type) {\n return memory_exports.Discard(type, [\"~kind\", \"type\", \"properties\", \"required\"]);\n }\n\n // node_modules/typebox/build/type/types/unknown.mjs\n function Unknown(options) {\n return memory_exports.Create({ [\"~kind\"]: \"Unknown\" }, {}, options);\n }\n function IsUnknown(value) {\n return IsKind(value, \"Unknown\");\n }\n\n // node_modules/typebox/build/type/types/cyclic.mjs\n function Cyclic($defs, $ref, options) {\n const defs = guard_exports.Keys($defs).reduce((result, key) => {\n return { ...result, [key]: memory_exports.Update($defs[key], {}, { $id: key }) };\n }, {});\n return memory_exports.Create({ [\"~kind\"]: \"Cyclic\" }, { $defs: defs, $ref }, options);\n }\n function IsCyclic(value) {\n return IsKind(value, \"Cyclic\");\n }\n\n // node_modules/typebox/build/type/types/unsafe.mjs\n function Unsafe(schema) {\n return memory_exports.Update(schema, { [\"~unsafe\"]: null }, {});\n }\n function IsUnsafe(value) {\n return guard_exports.IsObjectNotArray(value) && guard_exports.HasPropertyKey(value, \"~unsafe\") && guard_exports.IsNull(value[\"~unsafe\"]);\n }\n\n // node_modules/typebox/build/type/types/infer.mjs\n function Infer(...args) {\n const [name, extends_] = arguments_exports.Match(args, {\n 2: (name2, extends_2) => [name2, extends_2, extends_2],\n 1: (name2) => [name2, Unknown(), Unknown()]\n });\n return memory_exports.Create({ [\"~kind\"]: \"Infer\" }, { type: \"infer\", name, extends: extends_ }, {});\n }\n function IsInfer(value) {\n return IsKind(value, \"Infer\");\n }\n\n // node_modules/typebox/build/type/types/dependent.mjs\n function Dependent(if_, then_, else_, options = {}) {\n return memory_exports.Create({ \"~kind\": \"Dependent\" }, { if: if_, then: then_, else: else_ }, options);\n }\n function IsDependent(value) {\n return IsKind(value, \"Dependent\");\n }\n function DependentOptions(type) {\n return memory_exports.Discard(type, [\"~kind\", \"if\", \"then\", \"else\"]);\n }\n\n // node_modules/typebox/build/type/engine/enum/typescript_enum_to_enum_values.mjs\n function IsTypeScriptEnumLike(value) {\n return guard_exports.IsObjectNotArray(value);\n }\n function TypeScriptEnumToEnumValues(type) {\n const keys = guard_exports.Keys(type).filter((key) => isNaN(key));\n return keys.reduce((result, key) => [...result, type[key]], []);\n }\n\n // node_modules/typebox/build/type/types/enum.mjs\n function IsEnumValue(value) {\n return guard_exports.IsString(value) || guard_exports.IsNumber(value);\n }\n function Enum(value, options) {\n const values = IsTypeScriptEnumLike(value) ? TypeScriptEnumToEnumValues(value) : value;\n return memory_exports.Create({ \"~kind\": \"Enum\" }, { enum: values }, options);\n }\n function IsEnum2(value) {\n return IsKind(value, \"Enum\");\n }\n\n // node_modules/typebox/build/type/types/intersect.mjs\n function Intersect(types, options = {}) {\n return memory_exports.Create({ \"~kind\": \"Intersect\" }, { allOf: types }, options);\n }\n function IsIntersect(value) {\n return IsKind(value, \"Intersect\");\n }\n function IntersectOptions(type) {\n return memory_exports.Discard(type, [\"~kind\", \"allOf\"]);\n }\n\n // node_modules/typebox/build/type/types/_codec.mjs\n var EncodeBuilder = class {\n constructor(type, decode) {\n this.type = type;\n this.decode = decode;\n }\n Encode(callback) {\n const type = this.type;\n const decode = IsCodec(type) ? (value) => this.decode(type[\"~codec\"].decode(value)) : this.decode;\n const encode = IsCodec(type) ? (value) => type[\"~codec\"].encode(callback(value)) : callback;\n const codec = { decode, encode };\n return memory_exports.Update(this.type, { \"~codec\": codec }, {});\n }\n };\n var DecodeBuilder = class {\n constructor(type) {\n this.type = type;\n }\n Decode(callback) {\n return new EncodeBuilder(this.type, callback);\n }\n };\n function Codec(type) {\n return new DecodeBuilder(type);\n }\n function Decode2(type, callback) {\n return Codec(type).Decode(callback).Encode(() => {\n throw Error(\"Encode not implemented\");\n });\n }\n function Encode2(type, callback) {\n return Codec(type).Decode(() => {\n throw Error(\"Decode not implemented\");\n }).Encode(callback);\n }\n function IsCodec(value) {\n return IsSchema2(value) && guard_exports.HasPropertyKey(value, \"~codec\") && guard_exports.IsObject(value[\"~codec\"]) && guard_exports.HasPropertyKey(value[\"~codec\"], \"encode\") && guard_exports.HasPropertyKey(value[\"~codec\"], \"decode\");\n }\n\n // node_modules/typebox/build/type/types/_immutable.mjs\n function Immutable(type) {\n return AddImmutable(type);\n }\n function IsImmutable(value) {\n return IsSchema2(value) && guard_exports.HasPropertyKey(value, \"~immutable\");\n }\n\n // node_modules/typebox/build/type/action/_add_readonly.mjs\n function AddReadonlyDeferred(type, options = {}) {\n return Deferred(\"AddReadonly\", [type], options);\n }\n function AddReadonly(type, options = {}) {\n return AddReadonlyAction(type, options);\n }\n\n // node_modules/typebox/build/type/types/_readonly.mjs\n function Readonly(type) {\n return AddReadonly(type);\n }\n function IsReadonly(value) {\n return IsSchema2(value) && guard_exports.HasPropertyKey(value, \"~readonly\");\n }\n\n // node_modules/typebox/build/type/types/_refine.mjs\n function RefineAdd(type, refinement) {\n const refinements = IsRefine2(type) ? [...type[\"~refine\"], refinement] : [refinement];\n return memory_exports.Update(type, { \"~refine\": refinements }, {});\n }\n function Refine(...args) {\n const [type, check, error] = arguments_exports.Match(args, {\n 3: (type2, check2, error2) => [type2, check2, error2],\n 2: (type2, check2) => [type2, check2, () => \"Refine Error\"]\n });\n return RefineAdd(type, { check, error });\n }\n function IsRefinement(value) {\n return guard_exports.IsObjectNotArray(value) && guard_exports.HasPropertyKey(value, \"check\") && guard_exports.HasPropertyKey(value, \"error\") && guard_exports.IsFunction(value.check) && guard_exports.IsFunction(value.error);\n }\n function IsRefine2(value) {\n return IsSchema2(value) && guard_exports.HasPropertyKey(value, \"~refine\") && guard_exports.IsArray(value[\"~refine\"]) && guard_exports.Every(value[\"~refine\"], 0, (value2) => IsRefinement(value2));\n }\n\n // node_modules/typebox/build/type/types/bigint.mjs\n var BigIntPattern = \"-?(?:0|[1-9][0-9]*)n\";\n function BigInt2(options) {\n return memory_exports.Create({ \"~kind\": \"BigInt\" }, { type: \"bigint\" }, options);\n }\n function IsBigInt3(value) {\n return IsKind(value, \"BigInt\");\n }\n\n // node_modules/typebox/build/type/types/boolean.mjs\n function Boolean2(options) {\n return memory_exports.Create({ \"~kind\": \"Boolean\" }, { type: \"boolean\" }, options);\n }\n function IsBoolean4(value) {\n return IsKind(value, \"Boolean\");\n }\n\n // node_modules/typebox/build/type/types/identifier.mjs\n function Identifier(name) {\n return memory_exports.Create({ \"~kind\": \"Identifier\" }, { name });\n }\n function IsIdentifier2(value) {\n return IsKind(value, \"Identifier\");\n }\n\n // node_modules/typebox/build/type/types/integer.mjs\n var IntegerPattern = \"-?(?:0|[1-9][0-9]*)\";\n function Integer(options) {\n return memory_exports.Create({ \"~kind\": \"Integer\" }, { type: \"integer\" }, options);\n }\n function IsInteger3(value) {\n return IsKind(value, \"Integer\");\n }\n\n // node_modules/typebox/build/type/types/literal.mjs\n var InvalidLiteralValue = class extends Error {\n constructor(value) {\n super(`Invalid Literal value`);\n Object.defineProperty(this, \"cause\", {\n value: { value },\n writable: false,\n configurable: false,\n enumerable: false\n });\n }\n };\n function LiteralTypeName(value) {\n return guard_exports.IsBigInt(value) ? \"bigint\" : guard_exports.IsBoolean(value) ? \"boolean\" : guard_exports.IsNumber(value) ? \"number\" : guard_exports.IsString(value) ? \"string\" : (() => {\n throw new InvalidLiteralValue(value);\n })();\n }\n function Literal(value, options) {\n return memory_exports.Create({ \"~kind\": \"Literal\" }, { type: LiteralTypeName(value), const: value }, options);\n }\n function IsLiteralValue(value) {\n return guard_exports.IsBigInt(value) || guard_exports.IsBoolean(value) || guard_exports.IsNumber(value) || guard_exports.IsString(value);\n }\n function IsLiteralBigInt(value) {\n return IsLiteral(value) && guard_exports.IsBigInt(value.const);\n }\n function IsLiteralBoolean(value) {\n return IsLiteral(value) && guard_exports.IsBoolean(value.const);\n }\n function IsLiteralNumber(value) {\n return IsLiteral(value) && guard_exports.IsNumber(value.const);\n }\n function IsLiteralString(value) {\n return IsLiteral(value) && guard_exports.IsString(value.const);\n }\n function IsLiteral(value) {\n return IsKind(value, \"Literal\");\n }\n\n // node_modules/typebox/build/type/types/null.mjs\n function Null(options) {\n return memory_exports.Create({ \"~kind\": \"Null\" }, { type: \"null\" }, options);\n }\n function IsNull3(value) {\n return IsKind(value, \"Null\");\n }\n\n // node_modules/typebox/build/type/types/number.mjs\n var NumberPattern = \"-?(?:0|[1-9][0-9]*)(?:\\\\.[0-9]+)?\";\n function Number2(options) {\n return memory_exports.Create({ \"~kind\": \"Number\" }, { type: \"number\" }, options);\n }\n function IsNumber4(value) {\n return IsKind(value, \"Number\");\n }\n\n // node_modules/typebox/build/type/types/symbol.mjs\n function Symbol2(options) {\n return memory_exports.Create({ \"~kind\": \"Symbol\" }, { type: \"symbol\" }, options);\n }\n function IsSymbol3(value) {\n return IsKind(value, \"Symbol\");\n }\n\n // node_modules/typebox/build/type/types/parameter.mjs\n function Parameter(...args) {\n const [name, extends_, equals] = arguments_exports.Match(args, {\n 3: (name2, extends_2, equals2) => [name2, extends_2, equals2],\n 2: (name2, extends_2) => [name2, extends_2, extends_2],\n 1: (name2) => [name2, Unknown(), Unknown()]\n });\n return memory_exports.Create({ \"~kind\": \"Parameter\" }, { name, extends: extends_, equals }, {});\n }\n function IsParameter(value) {\n return IsKind(value, \"Parameter\");\n }\n\n // node_modules/typebox/build/type/types/string.mjs\n var StringPattern = \".*\";\n function String2(options) {\n return memory_exports.Create({ \"~kind\": \"String\" }, { type: \"string\" }, options);\n }\n function IsString4(value) {\n return IsKind(value, \"String\");\n }\n\n // node_modules/typebox/build/type/types/union.mjs\n function Union(anyOf, options = {}) {\n return memory_exports.Create({ \"~kind\": \"Union\" }, { anyOf }, options);\n }\n function IsUnion(value) {\n return IsKind(value, \"Union\");\n }\n function UnionOptions(type) {\n return memory_exports.Discard(type, [\"~kind\", \"anyOf\"]);\n }\n\n // node_modules/typebox/build/type/engine/patterns/pattern.mjs\n function ParsePatternIntoTypes(pattern) {\n const parsed = Pattern(pattern);\n const result = guard_exports.IsEqual(parsed.length, 2) ? parsed[0] : [];\n return result;\n }\n\n // node_modules/typebox/build/type/engine/template_literal/is_finite.mjs\n function FromLiteral(_value) {\n return true;\n }\n function FromTypesReduce(types) {\n return guard_exports.ShiftLeft(types, (left, right) => FromType(left) ? FromTypesReduce(right) : false, () => true);\n }\n function FromTypes(types) {\n const result = guard_exports.IsEqual(types.length, 0) ? false : FromTypesReduce(types);\n return result;\n }\n function FromType(type) {\n return IsUnion(type) ? FromTypes(type.anyOf) : IsLiteral(type) ? FromLiteral(type.const) : false;\n }\n function IsTemplateLiteralFinite(types) {\n const result = FromTypes(types);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/template_literal/create.mjs\n function TemplateLiteralCreate(pattern) {\n return memory_exports.Create({ [\"~kind\"]: \"TemplateLiteral\" }, { type: \"string\", pattern }, {});\n }\n\n // node_modules/typebox/build/type/engine/template_literal/decode.mjs\n function FromLiteralPush(variants, value, result = []) {\n return guard_exports.ShiftLeft(variants, (left, right) => FromLiteralPush(right, value, [...result, `${left}${value}`]), () => result);\n }\n function FromLiteral2(variants, value) {\n return guard_exports.IsEqual(variants.length, 0) ? [`${value}`] : FromLiteralPush(variants, value);\n }\n function FromUnion(variants, types, result = []) {\n return guard_exports.ShiftLeft(types, (left, right) => FromUnion(variants, right, [...result, ...FromType2(variants, left)]), () => result);\n }\n function FromType2(variants, type) {\n const result = IsUnion(type) ? FromUnion(variants, type.anyOf) : IsLiteral(type) ? FromLiteral2(variants, type.const) : Unreachable();\n return result;\n }\n function DecodeFromSpan(variants, types) {\n return guard_exports.ShiftLeft(types, (left, right) => DecodeFromSpan(FromType2(variants, left), right), () => variants);\n }\n function VariantsToLiterals(variants) {\n return variants.map((variant) => Literal(variant));\n }\n function DecodeTypesAsUnion(types) {\n const variants = DecodeFromSpan([], types);\n const literals = VariantsToLiterals(variants);\n const result = Union(literals);\n return result;\n }\n function DecodeTypes(types) {\n return guard_exports.IsEqual(types.length, 0) ? Unreachable() : (\n // Literal('') :\n guard_exports.IsEqual(types.length, 1) && IsLiteral(types[0]) ? types[0] : DecodeTypesAsUnion(types)\n );\n }\n function TemplateLiteralDecodeUnsafe(pattern) {\n const types = ParsePatternIntoTypes(pattern);\n const result = guard_exports.IsEqual(types.length, 0) ? String2() : IsTemplateLiteralFinite(types) ? DecodeTypes(types) : TemplateLiteralCreate(pattern);\n return result;\n }\n function TemplateLiteralDecode(pattern) {\n const decoded = TemplateLiteralDecodeUnsafe(pattern);\n const result = IsTemplateLiteral(decoded) ? String2() : decoded;\n return result;\n }\n\n // node_modules/typebox/build/type/engine/record/record_create.mjs\n function CreateRecord(key, value) {\n const type = \"object\";\n const patternProperties = { [key]: value };\n return memory_exports.Create({ [\"~kind\"]: \"Record\" }, { type, patternProperties });\n }\n\n // node_modules/typebox/build/type/engine/record/from_key_any.mjs\n function FromAnyKey(value) {\n return CreateRecord(StringKey, value);\n }\n\n // node_modules/typebox/build/type/engine/record/from_key_boolean.mjs\n function FromBooleanKey(value) {\n return _Object_({ true: value, false: value });\n }\n\n // node_modules/typebox/build/type/types/tuple.mjs\n function Tuple(types, options = {}) {\n const [items, minItems, additionalItems] = [types, types.length, false];\n return memory_exports.Create({ [\"~kind\"]: \"Tuple\" }, { type: \"array\", additionalItems, items, minItems }, options);\n }\n function IsTuple(value) {\n return IsKind(value, \"Tuple\");\n }\n function TupleOptions(type) {\n return memory_exports.Discard(type, [\"~kind\", \"type\", \"items\", \"minItems\", \"additionalItems\"]);\n }\n\n // node_modules/typebox/build/type/engine/readonly/instantiate_remove.mjs\n function RemoveReadonlyOperation(type) {\n return memory_exports.Discard(type, [\"~readonly\"]);\n }\n function RemoveReadonlyAction(type, options) {\n const result = memory_exports.Update(RemoveReadonlyOperation(type), {}, options);\n return result;\n }\n function RemoveReadonlyInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return RemoveReadonlyAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/action/_remove_readonly.mjs\n function RemoveReadonlyDeferred(type, options = {}) {\n return Deferred(\"RemoveReadonly\", [type], options);\n }\n function RemoveReadonly(type, options = {}) {\n return RemoveReadonlyAction(type, options);\n }\n\n // node_modules/typebox/build/type/engine/optional/instantiate_remove.mjs\n function RemoveOptionalOperation(type) {\n return memory_exports.Discard(type, [\"~optional\"]);\n }\n function RemoveOptionalAction(type, options) {\n const result = memory_exports.Update(RemoveOptionalOperation(type), {}, options);\n return result;\n }\n function RemoveOptionalInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return RemoveOptionalAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/action/_remove_optional.mjs\n function RemoveOptionalDeferred(type, options = {}) {\n return Deferred(\"RemoveOptional\", [type], options);\n }\n function RemoveOptional(type, options = {}) {\n return RemoveOptionalAction(type, options);\n }\n\n // node_modules/typebox/build/type/engine/tuple/to_object.mjs\n function TupleElementsToProperties(types) {\n const result = types.reduceRight((result2, right, index3) => {\n return { [index3]: right, ...result2 };\n }, {});\n return result;\n }\n function TupleToObject(type) {\n const properties = TupleElementsToProperties(type.items);\n const result = _Object_(properties);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/evaluate/composite.mjs\n function CanComposite(type) {\n return IsObject3(type) || IsTuple(type);\n }\n function IsReadonlyProperty(left, right) {\n return IsReadonly(left) ? IsReadonly(right) ? true : false : false;\n }\n function IsOptionalProperty(left, right) {\n return IsOptional(left) ? IsOptional(right) ? true : false : false;\n }\n function CompositeProperty(left, right) {\n const isReadonly = IsReadonlyProperty(left, right);\n const isOptional = IsOptionalProperty(left, right);\n const evaluated = EvaluateIntersect([left, right]);\n const property = RemoveReadonly(RemoveOptional(evaluated));\n return isReadonly && isOptional ? AddReadonly(AddOptional(property)) : isReadonly && !isOptional ? AddReadonly(property) : !isReadonly && isOptional ? AddOptional(property) : property;\n }\n function CompositePropertyKey(left, right, key) {\n return key in left ? key in right ? CompositeProperty(left[key], right[key]) : left[key] : key in right ? right[key] : Never();\n }\n function CompositeProperties(left, right) {\n const keys = /* @__PURE__ */ new Set([...guard_exports.Keys(left), ...guard_exports.Keys(right)]);\n const result = [...keys].reduce((result2, key) => {\n return { ...result2, [key]: CompositePropertyKey(left, right, key) };\n }, {});\n return result;\n }\n function GetProperties(type) {\n const result = IsObject3(type) ? type.properties : IsTuple(type) ? TupleElementsToProperties(type.items) : {};\n return result;\n }\n function Composite(left, right) {\n const leftProperties = GetProperties(left);\n const rightProperties = GetProperties(right);\n const properties = CompositeProperties(leftProperties, rightProperties);\n const result = _Object_(properties);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/evaluate/narrow.mjs\n function NarrowCompareRule(left, right) {\n const result = Compare(left, right);\n return guard_exports.IsEqual(result, CompareResultLeftInside) ? left : guard_exports.IsEqual(result, CompareResultRightInside) ? right : guard_exports.IsEqual(result, CompareResultEqual) ? right : Never();\n }\n function NarrowCompositeRule(left, right) {\n const canCompositeLeft = CanComposite(left);\n const canCompositeRight = CanComposite(right);\n return canCompositeLeft && canCompositeRight ? Composite(left, right) : canCompositeLeft && !canCompositeRight ? left : !canCompositeLeft && canCompositeRight ? right : NarrowCompareRule(left, right);\n }\n function Narrow(left, right) {\n return IsNever(left) ? left : IsAny(left) ? left : IsUnknown(left) ? right : IsNever(right) ? right : IsAny(right) ? right : IsUnknown(right) ? left : NarrowCompositeRule(left, right);\n }\n\n // node_modules/typebox/build/type/engine/evaluate/distribute.mjs\n function ShouldEvaluate(left, right) {\n const result = IsUnion(left) || IsUnion(right);\n return result;\n }\n function DistributeOperation(left, right) {\n const evaluatedLeft = EvaluateType(left);\n const evaluatedRight = EvaluateType(right);\n const shouldEvaluate = ShouldEvaluate(evaluatedLeft, evaluatedRight);\n const result = shouldEvaluate ? EvaluateIntersect([evaluatedLeft, evaluatedRight]) : Narrow(evaluatedLeft, evaluatedRight);\n return result;\n }\n function DistributeType(type, types, result = []) {\n return guard_exports.ShiftLeft(types, (left, right) => DistributeType(type, right, [...result, DistributeOperation(left, type)]), () => guard_exports.IsEqual(result.length, 0) ? [type] : result);\n }\n function DistributeUnion(types, distribution, result = []) {\n return guard_exports.ShiftLeft(types, (left, right) => DistributeUnion(right, distribution, [...result, ...Distribute([left], distribution)]), () => result);\n }\n function Distribute(types, result = []) {\n return guard_exports.ShiftLeft(types, (left, right) => IsUnion(left) ? Distribute(right, DistributeUnion(left.anyOf, result)) : Distribute(right, DistributeType(left, result)), () => result);\n }\n\n // node_modules/typebox/build/type/engine/exclude/operation.mjs\n function ExcludeType(left, right) {\n const check = Extends({}, left, right);\n const result = result_exports.IsExtendsTrueLike(check) ? [] : [left];\n return result;\n }\n function ExcludeUnion(left, right, result = []) {\n return guard_exports.ShiftLeft(left, (head, tail) => ExcludeUnion(tail, right, [...result, ...ExcludeType(head, right)]), () => result);\n }\n function ExcludeOperation(left, right) {\n const evaluated = EvaluateType(left);\n const canonical = IsUnion(evaluated) ? evaluated.anyOf : [evaluated];\n const remaining = ExcludeUnion(canonical, right);\n const result = EvaluateUnion(remaining);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/evaluate/evaluate.mjs\n function EvaluateDependent(if_, then_, else_) {\n const intersected = EvaluateIntersect([if_, then_]);\n const excluded = ExcludeOperation(else_, if_);\n const result = EvaluateUnion([intersected, excluded]);\n return result;\n }\n function EvaluateEnum(values, result = []) {\n return guard_exports.ShiftLeft(values, (left, right) => EvaluateEnum(right, [...result, Literal(left)]), () => EvaluateUnion(result));\n }\n function EvaluateIntersect(types) {\n const distribution = Distribute(types);\n const broadend = Broaden(distribution);\n const result = EvaluateUnion(broadend);\n return result;\n }\n function EvaluateTemplateLiteral(pattern) {\n const evaluated = TemplateLiteralDecode(pattern);\n const result = EvaluateType(evaluated);\n return result;\n }\n function EvaluateUnion(types) {\n const broadend = Broaden(types);\n const result = EvaluateUnionFast(broadend);\n return result;\n }\n function EvaluateType(type) {\n const result = IsDependent(type) ? EvaluateDependent(type.if, type.then, type.else) : IsEnum2(type) ? EvaluateEnum(type.enum) : IsIntersect(type) ? EvaluateIntersect(type.allOf) : IsTemplateLiteral(type) ? EvaluateTemplateLiteral(type.pattern) : IsUnion(type) ? EvaluateUnion(type.anyOf) : type;\n return result;\n }\n function EvaluateUnionFast(types) {\n const result = guard_exports.IsEqual(types.length, 1) ? types[0] : guard_exports.IsEqual(types.length, 0) ? Never() : Union(types);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/record/from_key_enum.mjs\n function FromEnumKey(values, value) {\n const unionKey = EvaluateEnum(values);\n const result = FromKey(unionKey, value);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/record/from_key_integer.mjs\n function FromIntegerKey(_key, value) {\n const result = CreateRecord(IntegerKey, value);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/record/from_key_intersect.mjs\n function FromIntersectKey(types, value) {\n const evaluatedKey = EvaluateIntersect(types);\n const result = FromKey(evaluatedKey, value);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/record/from_key_literal.mjs\n function FromLiteralKey(key, value) {\n return guard_exports.IsString(key) || guard_exports.IsNumber(key) ? _Object_({ [key]: value }) : guard_exports.IsEqual(key, false) ? _Object_({ false: value }) : guard_exports.IsEqual(key, true) ? _Object_({ true: value }) : _Object_({});\n }\n\n // node_modules/typebox/build/type/engine/record/from_key_number.mjs\n function FromNumberKey(_key, value) {\n const result = CreateRecord(NumberKey, value);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/record/from_key_string.mjs\n function FromStringKey(key, value) {\n return guard_exports.HasPropertyKey(key, \"pattern\") && (guard_exports.IsString(key.pattern) || key.pattern instanceof RegExp) ? CreateRecord(key.pattern.toString(), value) : CreateRecord(StringKey, value);\n }\n\n // node_modules/typebox/build/type/engine/record/from_key_template_literal.mjs\n function FromTemplateKey(pattern, value) {\n const types = ParsePatternIntoTypes(pattern);\n const finite = IsTemplateLiteralFinite(types);\n const result = finite ? FromKey(EvaluateTemplateLiteral(pattern), value) : CreateRecord(pattern, value);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/evaluate/flatten.mjs\n function FlattenType(type) {\n const result = IsUnion(type) ? Flatten(type.anyOf) : [type];\n return result;\n }\n function Flatten(types, result = []) {\n return guard_exports.ShiftLeft(types, (left, right) => Flatten(right, [...result, ...FlattenType(left)]), () => result);\n }\n\n // node_modules/typebox/build/type/engine/record/from_key_union.mjs\n function StringOrNumberCheck(types) {\n return types.some((type) => IsString4(type) || IsNumber4(type) || IsInteger3(type));\n }\n function TryBuildRecord(types, value) {\n return guard_exports.IsEqual(StringOrNumberCheck(types), true) ? CreateRecord(StringKey, value) : void 0;\n }\n function CreateProperties(types, value) {\n return types.reduce((result, left) => {\n return IsLiteral(left) && (guard_exports.IsString(left.const) || guard_exports.IsNumber(left.const)) ? { ...result, [left.const]: value } : result;\n }, {});\n }\n function CreateObject(types, value) {\n const properties = CreateProperties(types, value);\n const result = _Object_(properties);\n return result;\n }\n function FromUnionKey(types, value) {\n const flattened = Flatten(types);\n const record = TryBuildRecord(flattened, value);\n return IsSchema2(record) ? record : CreateObject(flattened, value);\n }\n\n // node_modules/typebox/build/type/engine/record/from_key.mjs\n function FromKey(key, value) {\n const result = IsAny(key) ? FromAnyKey(value) : IsBoolean4(key) ? FromBooleanKey(value) : IsEnum2(key) ? FromEnumKey(key.enum, value) : IsInteger3(key) ? FromIntegerKey(key, value) : IsIntersect(key) ? FromIntersectKey(key.allOf, value) : IsLiteral(key) ? FromLiteralKey(key.const, value) : IsNumber4(key) ? FromNumberKey(key, value) : IsUnion(key) ? FromUnionKey(key.anyOf, value) : IsString4(key) ? FromStringKey(key, value) : IsTemplateLiteral(key) ? FromTemplateKey(key.pattern, value) : _Object_({});\n return result;\n }\n\n // node_modules/typebox/build/type/engine/record/instantiate.mjs\n function RecordAction(key, value, options) {\n const result = CanInstantiate([key]) ? memory_exports.Update(FromKey(key, value), {}, options) : RecordDeferred(key, value, options);\n return result;\n }\n function RecordInstantiate(context2, state2, key, value, options) {\n const instantiatedKey = InstantiateType(context2, state2, key);\n const instantiatedValue = InstantiateType(context2, state2, value);\n return RecordAction(instantiatedKey, instantiatedValue, options);\n }\n\n // node_modules/typebox/build/type/types/record.mjs\n var IntegerKey = `^${IntegerPattern}$`;\n var NumberKey = `^${NumberPattern}$`;\n var StringKey = `^${StringPattern}$`;\n function RecordDeferred(key, value, options = {}) {\n return Deferred(\"Record\", [key, value], options);\n }\n function Record(key, value, options = {}) {\n return RecordAction(key, value, options);\n }\n function RecordFromPattern(pattern, value) {\n return CreateRecord(pattern, value);\n }\n function RecordPatternToType(pattern) {\n const result = guard_exports.IsEqual(pattern, StringKey) ? String2() : guard_exports.IsEqual(pattern, IntegerKey) ? Integer() : guard_exports.IsEqual(pattern, NumberKey) ? Number2() : TemplateLiteralDecodeUnsafe(pattern);\n return result;\n }\n function RecordPattern(type) {\n return guard_exports.Keys(type.patternProperties)[0];\n }\n function RecordKey(type) {\n const pattern = RecordPattern(type);\n const result = RecordPatternToType(pattern);\n return result;\n }\n function RecordValue(type) {\n return type.patternProperties[RecordPattern(type)];\n }\n function IsRecord(value) {\n return IsKind(value, \"Record\");\n }\n\n // node_modules/typebox/build/type/types/rest.mjs\n function Rest(type) {\n return memory_exports.Create({ \"~kind\": \"Rest\" }, { type: \"rest\", items: type }, {});\n }\n function IsRest(value) {\n return IsKind(value, \"Rest\");\n }\n\n // node_modules/typebox/build/type/types/this.mjs\n function This(options) {\n return memory_exports.Create({ [\"~kind\"]: \"This\" }, { $ref: \"#\" }, options);\n }\n function IsThis(value) {\n return IsKind(value, \"This\");\n }\n\n // node_modules/typebox/build/type/types/undefined.mjs\n function Undefined(options) {\n return memory_exports.Create({ \"~kind\": \"Undefined\" }, { type: \"undefined\" }, options);\n }\n function IsUndefined3(value) {\n return IsKind(value, \"Undefined\");\n }\n\n // node_modules/typebox/build/type/types/void.mjs\n function Void(options) {\n return memory_exports.Create({ \"~kind\": \"Void\" }, { type: \"void\" }, options);\n }\n function IsVoid(value) {\n return IsKind(value, \"Void\");\n }\n\n // node_modules/typebox/build/type/script/mapping.mjs\n function IntrinsicOrCall(ref, parameters) {\n return guard_exports.IsEqual(ref, \"Array\") ? _Array_(parameters[0]) : guard_exports.IsEqual(ref, \"Capitalize\") ? CapitalizeDeferred(parameters[0]) : guard_exports.IsEqual(ref, \"ConstructorParameters\") ? ConstructorParametersDeferred(parameters[0]) : guard_exports.IsEqual(ref, \"Evaluate\") ? EvaluateDeferred(parameters[0]) : guard_exports.IsEqual(ref, \"Exclude\") ? ExcludeDeferred(parameters[0], parameters[1]) : guard_exports.IsEqual(ref, \"Extract\") ? ExtractDeferred(parameters[0], parameters[1]) : guard_exports.IsEqual(ref, \"Index\") ? IndexDeferred(parameters[0], parameters[1]) : guard_exports.IsEqual(ref, \"InstanceType\") ? InstanceTypeDeferred(parameters[0]) : guard_exports.IsEqual(ref, \"Lowercase\") ? LowercaseDeferred(parameters[0]) : guard_exports.IsEqual(ref, \"NonNullable\") ? NonNullableDeferred(parameters[0]) : guard_exports.IsEqual(ref, \"Omit\") ? OmitDeferred(parameters[0], parameters[1]) : guard_exports.IsEqual(ref, \"Parameters\") ? ParametersDeferred(parameters[0]) : guard_exports.IsEqual(ref, \"Partial\") ? PartialDeferred(parameters[0]) : guard_exports.IsEqual(ref, \"Pick\") ? PickDeferred(parameters[0], parameters[1]) : guard_exports.IsEqual(ref, \"Readonly\") ? ReadonlyObjectDeferred(parameters[0]) : guard_exports.IsEqual(ref, \"KeyOf\") ? KeyOfDeferred(parameters[0]) : guard_exports.IsEqual(ref, \"Record\") ? RecordDeferred(parameters[0], parameters[1]) : guard_exports.IsEqual(ref, \"Required\") ? RequiredDeferred(parameters[0]) : guard_exports.IsEqual(ref, \"ReturnType\") ? ReturnTypeDeferred(parameters[0]) : guard_exports.IsEqual(ref, \"Uncapitalize\") ? UncapitalizeDeferred(parameters[0]) : guard_exports.IsEqual(ref, \"Uppercase\") ? UppercaseDeferred(parameters[0]) : CallConstruct(Ref2(ref), parameters);\n }\n function Unreachable2() {\n throw Error(\"Unreachable\");\n }\n function DelimitedDecode(input, result = []) {\n return guard_exports.ShiftLeft(input, (left, right) => DelimitedDecode(right, [...result, left[1]]), () => result);\n }\n function Delimited(input) {\n return guard_exports.IsEqual(input.length, 3) ? [input[0], ...DelimitedDecode(input[1])] : [];\n }\n function GenericParameterExtendsEqualsMapping(input) {\n return Parameter(input[0], input[2], input[4]);\n }\n function GenericParameterExtendsMapping(input) {\n return Parameter(input[0], input[2], input[2]);\n }\n function GenericParameterEqualsMapping(input) {\n return Parameter(input[0], Unknown(), input[2]);\n }\n function GenericParameterIdentifierMapping(input) {\n return Parameter(input, Unknown(), Unknown());\n }\n function GenericParameterMapping(input) {\n return input;\n }\n function GenericParameterListMapping(input) {\n return Delimited(input);\n }\n function GenericParametersMapping(input) {\n return input[1];\n }\n function GenericCallArgumentListMapping(input) {\n return Delimited(input);\n }\n function GenericCallArgumentsMapping(input) {\n return input[1];\n }\n function GenericCallMapping(input) {\n return IntrinsicOrCall(input[0], input[1]);\n }\n function OptionalSemiColonMapping(input) {\n return null;\n }\n function KeywordStringMapping(input) {\n return String2();\n }\n function KeywordNumberMapping(input) {\n return Number2();\n }\n function KeywordBooleanMapping(input) {\n return Boolean2();\n }\n function KeywordUndefinedMapping(input) {\n return Undefined();\n }\n function KeywordNullMapping(input) {\n return Null();\n }\n function KeywordIntegerMapping(input) {\n return Integer();\n }\n function KeywordBigIntMapping(input) {\n return BigInt2();\n }\n function KeywordUnknownMapping(input) {\n return Unknown();\n }\n function KeywordAnyMapping(input) {\n return Any();\n }\n function KeywordObjectMapping(input) {\n return _Object_({});\n }\n function KeywordNeverMapping(input) {\n return Never();\n }\n function KeywordSymbolMapping(input) {\n return Symbol2();\n }\n function KeywordVoidMapping(input) {\n return Void();\n }\n function KeywordThisMapping(input) {\n return This();\n }\n function LiteralBigIntMapping(input) {\n return Literal(BigInt(input));\n }\n function LiteralBooleanMapping(input) {\n return Literal(guard_exports.IsEqual(input, \"true\"));\n }\n function LiteralNumberMapping(input) {\n return Literal(parseFloat(input));\n }\n function LiteralStringMapping(input) {\n return Literal(input);\n }\n function TemplateInterpolateMapping(input) {\n return input[1];\n }\n function TemplateSpanMapping(input) {\n return Literal(input);\n }\n function TemplateBodyMapping(input) {\n return guard_exports.IsEqual(input.length, 3) ? [input[0], input[1], ...input[2]] : [input[0]];\n }\n function TemplateLiteralTypesMapping(input) {\n return input[1];\n }\n function TemplateLiteralMapping(input) {\n return TemplateLiteralDeferred(input);\n }\n function DependentMapping(input) {\n return guard_exports.IsEqual(input.length, 6) ? Dependent(input[1], input[3], input[5]) : Dependent(input[1], input[3], Unknown());\n }\n function KeyOfMapping(input) {\n return input.length > 0;\n }\n function IndexArrayMapping(input) {\n return input.reduce((result, current) => {\n return guard_exports.IsEqual(current.length, 3) ? [...result, [current[1]]] : [...result, []];\n }, []);\n }\n function ExtendsMapping(input) {\n return guard_exports.IsEqual(input.length, 6) ? [input[1], input[3], input[5]] : [];\n }\n function BaseMapping(input) {\n return guard_exports.IsArray(input) && guard_exports.IsEqual(input.length, 3) ? input[1] : input;\n }\n function WithMapping(input) {\n return guard_exports.IsEqual(input.length, 2) ? input[1] : [];\n }\n function FactorIndexArray(Type2, indexArray) {\n return indexArray.reduce((result, left) => {\n const _left = left;\n return guard_exports.IsEqual(_left.length, 1) ? IndexDeferred(result, _left[0]) : guard_exports.IsEqual(_left.length, 0) ? _Array_(result) : Unreachable2();\n }, Type2);\n }\n function FactorExtends(type, extend) {\n return guard_exports.IsEqual(extend.length, 3) ? ConditionalDeferred(type, extend[0], extend[1], extend[2]) : type;\n }\n function FactorWith(type, withClause) {\n return guard_exports.IsArray(withClause) && guard_exports.IsEqual(withClause.length, 0) ? type : WithDeferred(type, withClause);\n }\n function FactorMapping(input) {\n const [keyOf, type, indexArray, extend, withClause] = input;\n return FactorWith(keyOf ? FactorExtends(KeyOfDeferred(FactorIndexArray(type, indexArray)), extend) : FactorExtends(FactorIndexArray(type, indexArray), extend), withClause);\n }\n function ExprBinaryMapping(left, rest) {\n return guard_exports.IsEqual(rest.length, 3) ? (() => {\n const [operator, right, next] = rest;\n const Schema = ExprBinaryMapping(right, next);\n if (guard_exports.IsEqual(operator, \"&\")) {\n return IsIntersect(Schema) ? Intersect([left, ...Schema.allOf]) : Intersect([left, Schema]);\n }\n if (guard_exports.IsEqual(operator, \"|\")) {\n return IsUnion(Schema) ? Union([left, ...Schema.anyOf]) : Union([left, Schema]);\n }\n Unreachable2();\n })() : left;\n }\n function ExprTermTailMapping(input) {\n return input;\n }\n function ExprTermMapping(input) {\n const [left, rest] = input;\n return ExprBinaryMapping(left, rest);\n }\n function ExprTailMapping(input) {\n return input;\n }\n function ExprMapping(input) {\n const [left, rest] = input;\n return ExprBinaryMapping(left, rest);\n }\n function ExprReadonlyMapping(input) {\n return AddImmutableDeferred(input[1]);\n }\n function ExprPipeMapping(input) {\n return input[1];\n }\n function GenericTypeMapping(input) {\n return Generic(input[0], input[2]);\n }\n function InferTypeMapping(input) {\n return guard_exports.IsEqual(input.length, 4) ? Infer(input[1], input[3]) : guard_exports.IsEqual(input.length, 2) ? Infer(input[1], Unknown()) : Unreachable2();\n }\n function TypeMapping(input) {\n return input;\n }\n function PropertyKeyNumberMapping(input) {\n return `${input}`;\n }\n function PropertyKeyIdentMapping(input) {\n return input;\n }\n function PropertyKeyQuotedMapping(input) {\n return input;\n }\n function PropertyKeyIndexMapping(input) {\n return IsInteger3(input[3]) ? IntegerKey : IsNumber4(input[3]) ? NumberKey : IsSymbol3(input[3]) ? StringKey : IsString4(input[3]) ? StringKey : Unreachable2();\n }\n function PropertyKeyMapping(input) {\n return input;\n }\n function ReadonlyMapping(input) {\n return input.length > 0;\n }\n function OptionalMapping(input) {\n return input.length > 0;\n }\n function PropertyMapping(input) {\n const [isReadonly, key, isOptional, _colon, type] = input;\n return {\n [key]: isReadonly && isOptional ? AddReadonlyDeferred(AddOptionalDeferred(type)) : isReadonly && !isOptional ? AddReadonlyDeferred(type) : !isReadonly && isOptional ? AddOptionalDeferred(type) : type\n };\n }\n function PropertyDelimiterMapping(input) {\n return input;\n }\n function PropertyListMapping(input) {\n return Delimited(input);\n }\n function PropertiesReduce(propertyList) {\n return propertyList.reduce((result, left) => {\n const isPatternProperties = guard_exports.HasPropertyKey(left, IntegerKey) || guard_exports.HasPropertyKey(left, NumberKey) || guard_exports.HasPropertyKey(left, StringKey);\n return isPatternProperties ? [result[0], memory_exports.Assign(result[1], left)] : [memory_exports.Assign(result[0], left), result[1]];\n }, [{}, {}]);\n }\n function PropertiesMapping(input) {\n return PropertiesReduce(input[1]);\n }\n function _Object_Mapping(input) {\n const [properties, patternProperties] = input;\n const options = guard_exports.IsEqual(guard_exports.Keys(patternProperties).length, 0) ? {} : { patternProperties };\n return _Object_(properties, options);\n }\n function ElementNamedMapping(input) {\n return guard_exports.IsEqual(input.length, 5) ? AddReadonlyDeferred(AddOptionalDeferred(input[4])) : guard_exports.IsEqual(input.length, 3) ? input[2] : guard_exports.IsEqual(input.length, 4) ? guard_exports.IsEqual(input[2], \"readonly\") ? AddReadonlyDeferred(input[3]) : AddOptionalDeferred(input[3]) : Unreachable2();\n }\n function ElementBaseMapping(input) {\n if (!guard_exports.IsArray(input) || !guard_exports.IsEqual(input.length, 3))\n return input;\n const [isReadonly, type, isOptional] = input;\n return isReadonly && isOptional ? AddReadonlyDeferred(AddOptionalDeferred(type)) : isReadonly && !isOptional ? AddReadonlyDeferred(type) : !isReadonly && isOptional ? AddOptionalDeferred(type) : type;\n }\n function ElementMapping(input) {\n return guard_exports.IsEqual(input.length, 2) ? Rest(input[1]) : guard_exports.IsEqual(input.length, 1) ? input[0] : Unreachable2();\n }\n function ElementListMapping(input) {\n return Delimited(input);\n }\n function _Tuple_Mapping(input) {\n return Tuple(input[1]);\n }\n function ParameterReadonlyOptionalMapping(input) {\n return AddReadonlyDeferred(AddOptionalDeferred(input[4]));\n }\n function ParameterReadonlyMapping(input) {\n return AddReadonlyDeferred(input[3]);\n }\n function ParameterOptionalMapping(input) {\n return AddOptionalDeferred(input[3]);\n }\n function ParameterTypeMapping(input) {\n return input[2];\n }\n function ParameterBaseMapping(input) {\n return input;\n }\n function ParameterMapping(input) {\n return guard_exports.IsEqual(input.length, 2) ? Rest(input[1]) : guard_exports.IsEqual(input.length, 1) ? input[0] : Unreachable2();\n }\n function ParameterListMapping(input) {\n return Delimited(input);\n }\n function _Function_Mapping(input) {\n return _Function_(input[1], input[4]);\n }\n function _Constructor_Mapping(input) {\n return Constructor(input[2], input[5]);\n }\n function ApplyReadonly(state2, type) {\n return guard_exports.IsEqual(state2, \"remove\") ? RemoveReadonlyDeferred(type) : guard_exports.IsEqual(state2, \"add\") ? AddReadonlyDeferred(type) : type;\n }\n function MappedReadonlyMapping(input) {\n return guard_exports.IsEqual(input.length, 2) && guard_exports.IsEqual(input[0], \"-\") ? \"remove\" : guard_exports.IsEqual(input.length, 2) && guard_exports.IsEqual(input[0], \"+\") ? \"add\" : guard_exports.IsEqual(input.length, 1) ? \"add\" : \"none\";\n }\n function ApplyOptional(state2, type) {\n return guard_exports.IsEqual(state2, \"remove\") ? RemoveOptionalDeferred(type) : guard_exports.IsEqual(state2, \"add\") ? AddOptionalDeferred(type) : type;\n }\n function MappedOptionalMapping(input) {\n return guard_exports.IsEqual(input.length, 2) && guard_exports.IsEqual(input[0], \"-\") ? \"remove\" : guard_exports.IsEqual(input.length, 2) && guard_exports.IsEqual(input[0], \"+\") ? \"add\" : guard_exports.IsEqual(input.length, 1) ? \"add\" : \"none\";\n }\n function MappedAsMapping(input) {\n return guard_exports.IsEqual(input.length, 2) ? [input[1]] : [];\n }\n function _Mapped_Mapping(input) {\n return guard_exports.IsArray(input[6]) && guard_exports.IsEqual(input[6].length, 1) ? MappedDeferred(Identifier(input[3]), input[5], input[6][0], ApplyReadonly(input[1], ApplyOptional(input[8], input[10]))) : MappedDeferred(Identifier(input[3]), input[5], Ref2(input[3]), ApplyReadonly(input[1], ApplyOptional(input[8], input[10])));\n }\n function ReferenceMapping(input) {\n return Ref2(input);\n }\n function WithBigIntMapping(input) {\n return BigInt(input);\n }\n function WithNumberMapping(input) {\n return parseFloat(input);\n }\n function WithBooleanMapping(input) {\n return guard_exports.IsEqual(input, \"true\");\n }\n function WithStringMapping(input) {\n return input;\n }\n function WithNullMapping(input) {\n return null;\n }\n function WithUndefinedMapping(input) {\n return void 0;\n }\n function WithPropertyMapping(input) {\n return { [input[0]]: input[2] };\n }\n function WithPropertyListMapping(input) {\n return Delimited(input);\n }\n function WithObjectMappingReduce(propertyList) {\n return propertyList.reduce((result, left) => {\n return memory_exports.Assign(result, left);\n }, {});\n }\n function WithObjectMapping(input) {\n return WithObjectMappingReduce(input[1]);\n }\n function WithElementListMapping(input) {\n return Delimited(input);\n }\n function WithArrayMapping(input) {\n return input[1];\n }\n function WithValueMapping(input) {\n return input;\n }\n function PatternBigIntMapping(input) {\n return BigInt2();\n }\n function PatternStringMapping(input) {\n return String2();\n }\n function PatternNumberMapping(input) {\n return Number2();\n }\n function PatternIntegerMapping(input) {\n return Integer();\n }\n function PatternNeverMapping(input) {\n return Never();\n }\n function PatternTextMapping(input) {\n return Literal(input);\n }\n function PatternBaseMapping(input) {\n return input;\n }\n function PatternGroupMapping(input) {\n return Union(input[1]);\n }\n function PatternUnionMapping(input) {\n return input.length === 3 ? [...input[0], ...input[2]] : input.length === 1 ? [...input[0]] : [];\n }\n function PatternTermMapping(input) {\n return [input[0], ...input[1]];\n }\n function PatternBodyMapping(input) {\n return input;\n }\n function PatternMapping(input) {\n return input[1];\n }\n function InterfaceDeclarationHeritageListMapping(input) {\n return Delimited(input);\n }\n function InterfaceDeclarationHeritageMapping(input) {\n return guard_exports.IsEqual(input.length, 2) ? input[1] : [];\n }\n function InterfaceDeclarationGenericMapping(input) {\n const parameters = input[2];\n const heritage = input[3];\n const [properties, patternProperties] = input[4];\n const options = guard_exports.IsEqual(guard_exports.Keys(patternProperties).length, 0) ? {} : { patternProperties };\n return { [input[1]]: Generic(parameters, InterfaceDeferred(heritage, properties, options)) };\n }\n function InterfaceDeclarationMapping(input) {\n const heritage = input[2];\n const [properties, patternProperties] = input[3];\n const options = guard_exports.IsEqual(guard_exports.Keys(patternProperties).length, 0) ? {} : { patternProperties };\n return { [input[1]]: InterfaceDeferred(heritage, properties, options) };\n }\n function TypeAliasDeclarationGenericMapping(input) {\n return { [input[1]]: Generic(input[2], input[4]) };\n }\n function TypeAliasDeclarationMapping(input) {\n return { [input[1]]: input[3] };\n }\n function ExportKeywordMapping(input) {\n return null;\n }\n function ModuleDeclarationDelimiterMapping(input) {\n return input;\n }\n function ModuleDeclarationListMapping(input) {\n return Delimited(input);\n }\n function ModuleDeclarationMapping(input) {\n return input[1];\n }\n function ModuleMapping(input) {\n const [moduleDeclaration, moduleDeclarationList] = [input[0], input[1]];\n return ModuleDeferred(memory_exports.Assign(moduleDeclaration, PropertiesReduce(moduleDeclarationList)[0]));\n }\n function ScriptMapping(input) {\n return input;\n }\n\n // node_modules/typebox/build/type/script/token/internal/match.mjs\n function IsMatch(value) {\n return IsEqual(value.length, 2);\n }\n function Match3(input, ok, fail) {\n return IsMatch(input) ? ok(input[0], input[1]) : fail();\n }\n\n // node_modules/typebox/build/type/script/token/internal/take.mjs\n function TakeVariant(variant, input) {\n return IsEqual(input.indexOf(variant), 0) ? [variant, input.slice(variant.length)] : [];\n }\n function Take(variants, input) {\n for (let i = 0; i < variants.length; i++) {\n const result = TakeVariant(variants[i], input);\n if (IsMatch(result))\n return result;\n }\n return [];\n }\n\n // node_modules/typebox/build/type/script/token/internal/char.mjs\n function Range(start, end) {\n return Array.from({ length: end - start + 1 }, (_, i) => String.fromCharCode(start + i));\n }\n var Alpha = [\n ...Range(97, 122),\n // Lowercase\n ...Range(65, 90)\n // Uppercase\n ];\n var Zero = \"0\";\n var NonZero = Range(49, 57);\n var Digit = [Zero, ...NonZero];\n var WhiteSpace = \" \";\n var NewLine = \"\\n\";\n var UnderScore = \"_\";\n var Dot = \".\";\n var DollarSign = \"$\";\n var Hyphen = \"-\";\n\n // node_modules/typebox/build/type/script/token/internal/trim.mjs\n var LineComment = \"//\";\n var OpenComment = \"/*\";\n var CloseComment = \"*/\";\n function DiscardMultilineComment(input) {\n const index3 = input.indexOf(CloseComment);\n const result = IsEqual(index3, -1) ? \"\" : input.slice(index3 + 2);\n return result;\n }\n function DiscardLineComment(input) {\n const index3 = input.indexOf(NewLine);\n const result = IsEqual(index3, -1) ? \"\" : input.slice(index3);\n return result;\n }\n function TrimStartUntilNewline(input) {\n return input.replace(/^[ \\t\\r\\f\\v]+/, \"\");\n }\n function TrimWhitespace(input) {\n const trimmed = TrimStartUntilNewline(input);\n return trimmed.startsWith(OpenComment) ? TrimWhitespace(DiscardMultilineComment(trimmed.slice(2))) : trimmed.startsWith(LineComment) ? TrimWhitespace(DiscardLineComment(trimmed.slice(2))) : trimmed;\n }\n function Trim(input) {\n const trimmed = input.trimStart();\n return trimmed.startsWith(OpenComment) ? Trim(DiscardMultilineComment(trimmed.slice(2))) : trimmed.startsWith(LineComment) ? Trim(DiscardLineComment(trimmed.slice(2))) : trimmed;\n }\n\n // node_modules/typebox/build/type/script/token/internal/optional.mjs\n function Optional2(value, input) {\n return Match3(Take([value], input), (Optional4, Rest2) => [Optional4, Rest2], () => [\"\", input]);\n }\n\n // node_modules/typebox/build/type/script/token/internal/many.mjs\n function IsDiscard(discard, input) {\n return discard.includes(input);\n }\n function Many(allowed, discard, input, result = \"\") {\n return Match3(Take(allowed, input), (Char, Rest2) => IsDiscard(discard, Char) ? Many(allowed, discard, Rest2, result) : Many(allowed, discard, Rest2, `${result}${Char}`), () => [result, input]);\n }\n\n // node_modules/typebox/build/type/script/token/unsigned_integer.mjs\n function TakeNonZero(input) {\n return Take(NonZero, input);\n }\n var AllowedDigits = [...Digit, UnderScore];\n function TakeDigits(input) {\n return Many(AllowedDigits, [UnderScore], input);\n }\n function TakeUnsignedInteger(input) {\n return Match3(Take([Zero], input), (Zero2, ZeroRest) => [Zero2, ZeroRest], () => Match3(\n TakeNonZero(input),\n (NonZero2, NonZeroRest) => Match3(TakeDigits(NonZeroRest), (Digits, DigitsRest) => [`${NonZero2}${Digits}`, DigitsRest], () => []),\n // fail: did not match Digits\n () => []\n ));\n }\n function UnsignedInteger(input) {\n return TakeUnsignedInteger(Trim(input));\n }\n\n // node_modules/typebox/build/type/script/token/integer.mjs\n function TakeSign(input) {\n return Optional2(Hyphen, input);\n }\n function TakeSignedInteger(input) {\n return Match3(\n TakeSign(input),\n (Sign, SignRest) => Match3(UnsignedInteger(SignRest), (UnsignedInteger2, UnsignedIntegerRest) => [`${Sign}${UnsignedInteger2}`, UnsignedIntegerRest], () => []),\n // fail: did not match unsigned integer\n () => []\n );\n }\n function Integer2(input) {\n return TakeSignedInteger(Trim(input));\n }\n\n // node_modules/typebox/build/type/script/token/bigint.mjs\n function TakeBigInt(input) {\n return Match3(\n Integer2(input),\n (Integer3, IntegerRest) => Match3(Take([\"n\"], IntegerRest), (_N, NRest) => [`${Integer3}`, NRest], () => []),\n // fail: did not match 'n'\n () => []\n );\n }\n function BigInt3(input) {\n return TakeBigInt(input);\n }\n\n // node_modules/typebox/build/type/script/token/const.mjs\n function TakeConst(const_, input) {\n return Take([const_], input);\n }\n function Const(const_, input) {\n return IsEqual(const_, \"\") ? [\"\", input] : const_.startsWith(NewLine) ? TakeConst(const_, TrimWhitespace(input)) : const_.startsWith(WhiteSpace) ? TakeConst(const_, input) : TakeConst(const_, Trim(input));\n }\n\n // node_modules/typebox/build/type/script/token/ident.mjs\n var Initial = [...Alpha, UnderScore, DollarSign];\n function TakeInitial(input) {\n return Take(Initial, input);\n }\n var Remaining = [...Initial, ...Digit];\n function TakeRemaining(input, result = \"\") {\n return Match3(Take(Remaining, input), (Remaining2, RemainingRest) => TakeRemaining(RemainingRest, `${result}${Remaining2}`), () => [result, input]);\n }\n function TakeIdent(input) {\n return Match3(\n TakeInitial(input),\n (Initial2, InitialRest) => Match3(TakeRemaining(InitialRest), (Remaining2, RemainingRest) => [`${Initial2}${Remaining2}`, RemainingRest], () => []),\n // fail: did not match Remaining\n () => []\n );\n }\n function Ident(input) {\n return TakeIdent(Trim(input));\n }\n\n // node_modules/typebox/build/type/script/token/unsigned_number.mjs\n var AllowedDigits2 = [...Digit, UnderScore];\n function IsLeadingDot(input) {\n return IsMatch(Take([Dot], input));\n }\n function TakeFractional(input) {\n return Match3(Many(AllowedDigits2, [UnderScore], input), (Digits, DigitsRest) => IsEqual(Digits, \"\") ? [] : [Digits, DigitsRest], () => []);\n }\n function LeadingDot(input) {\n return Match3(\n Take([Dot], input),\n (Dot2, DotRest) => Match3(TakeFractional(DotRest), (Fractional, FractionalRest) => [`0${Dot2}${Fractional}`, FractionalRest], () => []),\n // fail: did not match Fractional\n () => []\n );\n }\n function LeadingInteger(input) {\n return Match3(\n UnsignedInteger(input),\n (Integer3, IntegerRest) => Match3(\n Take([Dot], IntegerRest),\n (Dot2, DotRest) => Match3(TakeFractional(DotRest), (Fractional, FractionalRest) => [`${Integer3}${Dot2}${Fractional}`, FractionalRest], () => [`${Integer3}`, DotRest]),\n // fail: did not match Fractional, use Integer\n () => [`${Integer3}`, IntegerRest]\n ),\n // fail: did not match Dot, use Integer\n () => []\n );\n }\n function TakeUnsignedNumber(input) {\n return IsLeadingDot(input) ? LeadingDot(input) : LeadingInteger(input);\n }\n function UnsignedNumber(input) {\n return TakeUnsignedNumber(Trim(input));\n }\n\n // node_modules/typebox/build/type/script/token/number.mjs\n function TakeSign2(input) {\n return Optional2(Hyphen, input);\n }\n function TakeSignedNumber(input) {\n return Match3(\n TakeSign2(input),\n (Sign, SignRest) => Match3(UnsignedNumber(SignRest), (UnsignedInteger2, UnsignedIntegerRest) => [`${Sign}${UnsignedInteger2}`, UnsignedIntegerRest], () => []),\n // fail: did not match unsigned integer\n () => []\n );\n }\n function Number3(input) {\n return TakeSignedNumber(Trim(input));\n }\n\n // node_modules/typebox/build/type/script/token/until.mjs\n function TakeOne(input) {\n const result = IsEqual(input, \"\") ? [] : [input.slice(0, 1), input.slice(1)];\n return result;\n }\n function IsInputMatchSentinal(end, input) {\n return ShiftLeft(end, (left, right) => input.startsWith(left) ? true : IsInputMatchSentinal(right, input), () => false);\n }\n function Until(end, input, result = \"\") {\n return Match3(\n TakeOne(input),\n (One, Rest2) => IsInputMatchSentinal(end, input) ? [result, input] : Until(end, Rest2, `${result}${One}`),\n () => []\n );\n }\n\n // node_modules/typebox/build/type/script/token/span.mjs\n function MultiLine(start, end, input) {\n return Match3(\n Take([start], input),\n (_, Rest2) => Match3(\n Until([end], Rest2),\n (Until2, UntilRest) => Match3(Take([end], UntilRest), (_2, Rest3) => [`${Until2}`, Rest3], () => []),\n // fail: did not match End\n () => []\n ),\n // fail: did not match Until\n () => []\n );\n }\n function SingleLine(start, end, input) {\n return Match3(\n Take([start], input),\n (_, Rest2) => Match3(\n Until([NewLine, end], Rest2),\n (Until2, UntilRest) => Match3(Take([end], UntilRest), (_2, EndRest) => [`${Until2}`, EndRest], () => []),\n // fail: did not match End\n () => []\n ),\n // fail: did not match Until\n () => []\n );\n }\n function Span(start, end, multiLine, input) {\n return multiLine ? MultiLine(start, end, Trim(input)) : SingleLine(start, end, Trim(input));\n }\n\n // node_modules/typebox/build/type/script/token/string.mjs\n function TakeInitial2(quotes, input) {\n return Take(quotes, input);\n }\n function TakeSpan(quote, input) {\n return Span(quote, quote, false, input);\n }\n function TakeString(quotes, input) {\n return Match3(TakeInitial2(quotes, input), (Initial2, InitialRest) => TakeSpan(Initial2, `${Initial2}${InitialRest}`), () => []);\n }\n function String3(quotes, input) {\n return TakeString(quotes, Trim(input));\n }\n\n // node_modules/typebox/build/type/script/token/until_1.mjs\n function Until_1(end, input) {\n return Match3(Until(end, input), (Until2, UntilRest) => IsEqual(Until2, \"\") ? [] : [Until2, UntilRest], () => []);\n }\n\n // node_modules/typebox/build/type/script/parser.mjs\n var If2 = (result, left, right = () => []) => result.length === 2 ? left(result) : right();\n var GenericParameterExtendsEquals = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(Const(\"extends\", input2), ([_1, input3]) => If2(Type(input3), ([_2, input4]) => If2(Const(\"=\", input4), ([_3, input5]) => If2(Type(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [GenericParameterExtendsEqualsMapping(_0), input2]);\n var GenericParameterExtends = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(Const(\"extends\", input2), ([_1, input3]) => If2(Type(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [GenericParameterExtendsMapping(_0), input2]);\n var GenericParameterEquals = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(Const(\"=\", input2), ([_1, input3]) => If2(Type(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [GenericParameterEqualsMapping(_0), input2]);\n var GenericParameterIdentifier = (input) => If2(Ident(input), ([_0, input2]) => [GenericParameterIdentifierMapping(_0), input2]);\n var GenericParameter = (input) => If2(If2(GenericParameterExtendsEquals(input), ([_0, input2]) => [_0, input2], () => If2(GenericParameterExtends(input), ([_0, input2]) => [_0, input2], () => If2(GenericParameterEquals(input), ([_0, input2]) => [_0, input2], () => If2(GenericParameterIdentifier(input), ([_0, input2]) => [_0, input2], () => [])))), ([_0, input2]) => [GenericParameterMapping(_0), input2]);\n var GenericParameterList_0 = (input, result = []) => If2(If2(Const(\",\", input), ([_0, input2]) => If2(GenericParameter(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => GenericParameterList_0(input2, [...result, _0]), () => [result, input]);\n var GenericParameterList = (input) => If2(If2(If2(GenericParameter(input), ([_0, input2]) => If2(GenericParameterList_0(input2), ([_1, input3]) => If2(If2(Const(\",\", input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [GenericParameterListMapping(_0), input2]);\n var GenericParameters = (input) => If2(If2(Const(\"<\", input), ([_0, input2]) => If2(GenericParameterList(input2), ([_1, input3]) => If2(Const(\">\", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [GenericParametersMapping(_0), input2]);\n var GenericCallArgumentList_0 = (input, result = []) => If2(If2(Const(\",\", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => GenericCallArgumentList_0(input2, [...result, _0]), () => [result, input]);\n var GenericCallArgumentList = (input) => If2(If2(If2(Type(input), ([_0, input2]) => If2(GenericCallArgumentList_0(input2), ([_1, input3]) => If2(If2(Const(\",\", input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [GenericCallArgumentListMapping(_0), input2]);\n var GenericCallArguments = (input) => If2(If2(Const(\"<\", input), ([_0, input2]) => If2(GenericCallArgumentList(input2), ([_1, input3]) => If2(Const(\">\", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [GenericCallArgumentsMapping(_0), input2]);\n var GenericCall = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(GenericCallArguments(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [GenericCallMapping(_0), input2]);\n var OptionalSemiColon = (input) => If2(If2(If2(Const(\";\", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [OptionalSemiColonMapping(_0), input2]);\n var KeywordString = (input) => If2(Const(\"string\", input), ([_0, input2]) => [KeywordStringMapping(_0), input2]);\n var KeywordNumber = (input) => If2(Const(\"number\", input), ([_0, input2]) => [KeywordNumberMapping(_0), input2]);\n var KeywordBoolean = (input) => If2(Const(\"boolean\", input), ([_0, input2]) => [KeywordBooleanMapping(_0), input2]);\n var KeywordUndefined = (input) => If2(Const(\"undefined\", input), ([_0, input2]) => [KeywordUndefinedMapping(_0), input2]);\n var KeywordNull = (input) => If2(Const(\"null\", input), ([_0, input2]) => [KeywordNullMapping(_0), input2]);\n var KeywordInteger = (input) => If2(Const(\"integer\", input), ([_0, input2]) => [KeywordIntegerMapping(_0), input2]);\n var KeywordBigInt = (input) => If2(Const(\"bigint\", input), ([_0, input2]) => [KeywordBigIntMapping(_0), input2]);\n var KeywordUnknown = (input) => If2(Const(\"unknown\", input), ([_0, input2]) => [KeywordUnknownMapping(_0), input2]);\n var KeywordAny = (input) => If2(Const(\"any\", input), ([_0, input2]) => [KeywordAnyMapping(_0), input2]);\n var KeywordObject = (input) => If2(Const(\"object\", input), ([_0, input2]) => [KeywordObjectMapping(_0), input2]);\n var KeywordNever = (input) => If2(Const(\"never\", input), ([_0, input2]) => [KeywordNeverMapping(_0), input2]);\n var KeywordSymbol = (input) => If2(Const(\"symbol\", input), ([_0, input2]) => [KeywordSymbolMapping(_0), input2]);\n var KeywordVoid = (input) => If2(Const(\"void\", input), ([_0, input2]) => [KeywordVoidMapping(_0), input2]);\n var KeywordThis = (input) => If2(Const(\"this\", input), ([_0, input2]) => [KeywordThisMapping(_0), input2]);\n var TemplateInterpolate = (input) => If2(If2(Const(\"${\", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => If2(Const(\"}\", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [TemplateInterpolateMapping(_0), input2]);\n var TemplateSpan = (input) => If2(Until([\"${\", \"`\"], input), ([_0, input2]) => [TemplateSpanMapping(_0), input2]);\n var TemplateBody = (input) => If2(If2(If2(TemplateSpan(input), ([_0, input2]) => If2(TemplateInterpolate(input2), ([_1, input3]) => If2(TemplateBody(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2(If2(TemplateSpan(input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2(If2(TemplateSpan(input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => []))), ([_0, input2]) => [TemplateBodyMapping(_0), input2]);\n var TemplateLiteralTypes = (input) => If2(If2(Const(\"`\", input), ([_0, input2]) => If2(TemplateBody(input2), ([_1, input3]) => If2(Const(\"`\", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [TemplateLiteralTypesMapping(_0), input2]);\n var TemplateLiteral = (input) => If2(TemplateLiteralTypes(input), ([_0, input2]) => [TemplateLiteralMapping(_0), input2]);\n var Dependent2 = (input) => If2(If2(If2(Const(\"if\", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => If2(Const(\"then\", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => If2(Const(\"else\", input5), ([_4, input6]) => If2(Type(input6), ([_5, input7]) => [[_0, _1, _2, _3, _4, _5], input7])))))), ([_0, input2]) => [_0, input2], () => If2(If2(Const(\"if\", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => If2(Const(\"then\", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [DependentMapping(_0), input2]);\n var LiteralBigInt = (input) => If2(BigInt3(input), ([_0, input2]) => [LiteralBigIntMapping(_0), input2]);\n var LiteralBoolean = (input) => If2(If2(Const(\"true\", input), ([_0, input2]) => [_0, input2], () => If2(Const(\"false\", input), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [LiteralBooleanMapping(_0), input2]);\n var LiteralNumber = (input) => If2(Number3(input), ([_0, input2]) => [LiteralNumberMapping(_0), input2]);\n var LiteralString = (input) => If2(String3([\"'\", '\"'], input), ([_0, input2]) => [LiteralStringMapping(_0), input2]);\n var KeyOf = (input) => If2(If2(If2(Const(\"keyof\", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [KeyOfMapping(_0), input2]);\n var IndexArray_0 = (input, result = []) => If2(If2(If2(Const(\"[\", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => If2(Const(\"]\", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2(If2(Const(\"[\", input), ([_0, input2]) => If2(Const(\"]\", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => IndexArray_0(input2, [...result, _0]), () => [result, input]);\n var IndexArray = (input) => If2(IndexArray_0(input), ([_0, input2]) => [IndexArrayMapping(_0), input2]);\n var Extends2 = (input) => If2(If2(If2(Const(\"extends\", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => If2(Const(\"?\", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => If2(Const(\":\", input5), ([_4, input6]) => If2(Type(input6), ([_5, input7]) => [[_0, _1, _2, _3, _4, _5], input7])))))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ExtendsMapping(_0), input2]);\n var Base2 = (input) => If2(If2(If2(Const(\"(\", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => If2(Const(\")\", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2(KeywordString(input), ([_0, input2]) => [_0, input2], () => If2(KeywordNumber(input), ([_0, input2]) => [_0, input2], () => If2(KeywordBoolean(input), ([_0, input2]) => [_0, input2], () => If2(KeywordUndefined(input), ([_0, input2]) => [_0, input2], () => If2(KeywordNull(input), ([_0, input2]) => [_0, input2], () => If2(KeywordInteger(input), ([_0, input2]) => [_0, input2], () => If2(KeywordBigInt(input), ([_0, input2]) => [_0, input2], () => If2(KeywordUnknown(input), ([_0, input2]) => [_0, input2], () => If2(KeywordAny(input), ([_0, input2]) => [_0, input2], () => If2(KeywordObject(input), ([_0, input2]) => [_0, input2], () => If2(KeywordNever(input), ([_0, input2]) => [_0, input2], () => If2(KeywordSymbol(input), ([_0, input2]) => [_0, input2], () => If2(KeywordVoid(input), ([_0, input2]) => [_0, input2], () => If2(KeywordThis(input), ([_0, input2]) => [_0, input2], () => If2(LiteralBigInt(input), ([_0, input2]) => [_0, input2], () => If2(LiteralBoolean(input), ([_0, input2]) => [_0, input2], () => If2(LiteralNumber(input), ([_0, input2]) => [_0, input2], () => If2(LiteralString(input), ([_0, input2]) => [_0, input2], () => If2(TemplateLiteral(input), ([_0, input2]) => [_0, input2], () => If2(Dependent2(input), ([_0, input2]) => [_0, input2], () => If2(_Object_2(input), ([_0, input2]) => [_0, input2], () => If2(_Tuple_(input), ([_0, input2]) => [_0, input2], () => If2(_Constructor_(input), ([_0, input2]) => [_0, input2], () => If2(_Function_2(input), ([_0, input2]) => [_0, input2], () => If2(_Mapped_(input), ([_0, input2]) => [_0, input2], () => If2(GenericCall(input), ([_0, input2]) => [_0, input2], () => If2(Reference(input), ([_0, input2]) => [_0, input2], () => [])))))))))))))))))))))))))))), ([_0, input2]) => [BaseMapping(_0), input2]);\n var With = (input) => If2(If2(If2(Const(\"with\", input), ([_0, input2]) => If2(WithObject(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [WithMapping(_0), input2]);\n var Factor = (input) => If2(If2(KeyOf(input), ([_0, input2]) => If2(Base2(input2), ([_1, input3]) => If2(IndexArray(input3), ([_2, input4]) => If2(Extends2(input4), ([_3, input5]) => If2(With(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [FactorMapping(_0), input2]);\n var ExprTermTail = (input) => If2(If2(If2(Const(\"&\", input), ([_0, input2]) => If2(Factor(input2), ([_1, input3]) => If2(ExprTermTail(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ExprTermTailMapping(_0), input2]);\n var ExprTerm = (input) => If2(If2(Factor(input), ([_0, input2]) => If2(ExprTermTail(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [ExprTermMapping(_0), input2]);\n var ExprTail = (input) => If2(If2(If2(Const(\"|\", input), ([_0, input2]) => If2(ExprTerm(input2), ([_1, input3]) => If2(ExprTail(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ExprTailMapping(_0), input2]);\n var Expr = (input) => If2(If2(ExprTerm(input), ([_0, input2]) => If2(ExprTail(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [ExprMapping(_0), input2]);\n var ExprReadonly = (input) => If2(If2(Const(\"readonly\", input), ([_0, input2]) => If2(Expr(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [ExprReadonlyMapping(_0), input2]);\n var ExprPipe = (input) => If2(If2(Const(\"|\", input), ([_0, input2]) => If2(Expr(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [ExprPipeMapping(_0), input2]);\n var GenericType = (input) => If2(If2(GenericParameters(input), ([_0, input2]) => If2(Const(\"=\", input2), ([_1, input3]) => If2(Type(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [GenericTypeMapping(_0), input2]);\n var InferType = (input) => If2(If2(If2(Const(\"infer\", input), ([_0, input2]) => If2(Ident(input2), ([_1, input3]) => If2(Const(\"extends\", input3), ([_2, input4]) => If2(Expr(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [_0, input2], () => If2(If2(Const(\"infer\", input), ([_0, input2]) => If2(Ident(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [InferTypeMapping(_0), input2]);\n var Type = (input) => If2(If2(InferType(input), ([_0, input2]) => [_0, input2], () => If2(ExprPipe(input), ([_0, input2]) => [_0, input2], () => If2(ExprReadonly(input), ([_0, input2]) => [_0, input2], () => If2(Expr(input), ([_0, input2]) => [_0, input2], () => [])))), ([_0, input2]) => [TypeMapping(_0), input2]);\n var PropertyKeyNumber = (input) => If2(Number3(input), ([_0, input2]) => [PropertyKeyNumberMapping(_0), input2]);\n var PropertyKeyIdent = (input) => If2(Ident(input), ([_0, input2]) => [PropertyKeyIdentMapping(_0), input2]);\n var PropertyKeyQuoted = (input) => If2(String3([\"'\", '\"'], input), ([_0, input2]) => [PropertyKeyQuotedMapping(_0), input2]);\n var PropertyKeyIndex = (input) => If2(If2(Const(\"[\", input), ([_0, input2]) => If2(Ident(input2), ([_1, input3]) => If2(Const(\":\", input3), ([_2, input4]) => If2(If2(KeywordInteger(input4), ([_02, input5]) => [_02, input5], () => If2(KeywordNumber(input4), ([_02, input5]) => [_02, input5], () => If2(KeywordString(input4), ([_02, input5]) => [_02, input5], () => If2(KeywordSymbol(input4), ([_02, input5]) => [_02, input5], () => [])))), ([_3, input5]) => If2(Const(\"]\", input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [PropertyKeyIndexMapping(_0), input2]);\n var PropertyKey = (input) => If2(If2(PropertyKeyNumber(input), ([_0, input2]) => [_0, input2], () => If2(PropertyKeyIdent(input), ([_0, input2]) => [_0, input2], () => If2(PropertyKeyQuoted(input), ([_0, input2]) => [_0, input2], () => If2(PropertyKeyIndex(input), ([_0, input2]) => [_0, input2], () => [])))), ([_0, input2]) => [PropertyKeyMapping(_0), input2]);\n var Readonly2 = (input) => If2(If2(If2(Const(\"readonly\", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ReadonlyMapping(_0), input2]);\n var Optional3 = (input) => If2(If2(If2(Const(\"?\", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [OptionalMapping(_0), input2]);\n var Property = (input) => If2(If2(Readonly2(input), ([_0, input2]) => If2(PropertyKey(input2), ([_1, input3]) => If2(Optional3(input3), ([_2, input4]) => If2(Const(\":\", input4), ([_3, input5]) => If2(Type(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [PropertyMapping(_0), input2]);\n var PropertyDelimiter = (input) => If2(If2(If2(Const(\",\", input), ([_0, input2]) => If2(Const(\"\\n\", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(Const(\";\", input), ([_0, input2]) => If2(Const(\"\\n\", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(Const(\",\", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2(If2(Const(\";\", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2(If2(Const(\"\\n\", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => []))))), ([_0, input2]) => [PropertyDelimiterMapping(_0), input2]);\n var PropertyList_0 = (input, result = []) => If2(If2(PropertyDelimiter(input), ([_0, input2]) => If2(Property(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => PropertyList_0(input2, [...result, _0]), () => [result, input]);\n var PropertyList = (input) => If2(If2(If2(Property(input), ([_0, input2]) => If2(PropertyList_0(input2), ([_1, input3]) => If2(If2(PropertyDelimiter(input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [PropertyListMapping(_0), input2]);\n var Properties = (input) => If2(If2(Const(\"{\", input), ([_0, input2]) => If2(PropertyList(input2), ([_1, input3]) => If2(Const(\"}\", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [PropertiesMapping(_0), input2]);\n var _Object_2 = (input) => If2(Properties(input), ([_0, input2]) => [_Object_Mapping(_0), input2]);\n var ElementNamed = (input) => If2(If2(If2(Ident(input), ([_0, input2]) => If2(Const(\"?\", input2), ([_1, input3]) => If2(Const(\":\", input3), ([_2, input4]) => If2(Const(\"readonly\", input4), ([_3, input5]) => If2(Type(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [_0, input2], () => If2(If2(Ident(input), ([_0, input2]) => If2(Const(\":\", input2), ([_1, input3]) => If2(Const(\"readonly\", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [_0, input2], () => If2(If2(Ident(input), ([_0, input2]) => If2(Const(\"?\", input2), ([_1, input3]) => If2(Const(\":\", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [_0, input2], () => If2(If2(Ident(input), ([_0, input2]) => If2(Const(\":\", input2), ([_1, input3]) => If2(Type(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => [])))), ([_0, input2]) => [ElementNamedMapping(_0), input2]);\n var ElementBase = (input) => If2(If2(ElementNamed(input), ([_0, input2]) => [_0, input2], () => If2(If2(Readonly2(input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => If2(Optional3(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ElementBaseMapping(_0), input2]);\n var Element = (input) => If2(If2(If2(Const(\"...\", input), ([_0, input2]) => If2(ElementBase(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(ElementBase(input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ElementMapping(_0), input2]);\n var ElementList_0 = (input, result = []) => If2(If2(Const(\",\", input), ([_0, input2]) => If2(Element(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => ElementList_0(input2, [...result, _0]), () => [result, input]);\n var ElementList = (input) => If2(If2(If2(Element(input), ([_0, input2]) => If2(ElementList_0(input2), ([_1, input3]) => If2(If2(Const(\",\", input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ElementListMapping(_0), input2]);\n var _Tuple_ = (input) => If2(If2(Const(\"[\", input), ([_0, input2]) => If2(ElementList(input2), ([_1, input3]) => If2(Const(\"]\", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_Tuple_Mapping(_0), input2]);\n var ParameterReadonlyOptional = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(Const(\"?\", input2), ([_1, input3]) => If2(Const(\":\", input3), ([_2, input4]) => If2(Const(\"readonly\", input4), ([_3, input5]) => If2(Type(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [ParameterReadonlyOptionalMapping(_0), input2]);\n var ParameterReadonly = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(Const(\":\", input2), ([_1, input3]) => If2(Const(\"readonly\", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [ParameterReadonlyMapping(_0), input2]);\n var ParameterOptional = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(Const(\"?\", input2), ([_1, input3]) => If2(Const(\":\", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [ParameterOptionalMapping(_0), input2]);\n var ParameterType = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(Const(\":\", input2), ([_1, input3]) => If2(Type(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [ParameterTypeMapping(_0), input2]);\n var ParameterBase = (input) => If2(If2(ParameterReadonlyOptional(input), ([_0, input2]) => [_0, input2], () => If2(ParameterReadonly(input), ([_0, input2]) => [_0, input2], () => If2(ParameterOptional(input), ([_0, input2]) => [_0, input2], () => If2(ParameterType(input), ([_0, input2]) => [_0, input2], () => [])))), ([_0, input2]) => [ParameterBaseMapping(_0), input2]);\n var Parameter2 = (input) => If2(If2(If2(Const(\"...\", input), ([_0, input2]) => If2(ParameterBase(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(ParameterBase(input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ParameterMapping(_0), input2]);\n var ParameterList_0 = (input, result = []) => If2(If2(Const(\",\", input), ([_0, input2]) => If2(Parameter2(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => ParameterList_0(input2, [...result, _0]), () => [result, input]);\n var ParameterList = (input) => If2(If2(If2(Parameter2(input), ([_0, input2]) => If2(ParameterList_0(input2), ([_1, input3]) => If2(If2(Const(\",\", input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ParameterListMapping(_0), input2]);\n var _Function_2 = (input) => If2(If2(Const(\"(\", input), ([_0, input2]) => If2(ParameterList(input2), ([_1, input3]) => If2(Const(\")\", input3), ([_2, input4]) => If2(Const(\"=>\", input4), ([_3, input5]) => If2(Type(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [_Function_Mapping(_0), input2]);\n var _Constructor_ = (input) => If2(If2(Const(\"new\", input), ([_0, input2]) => If2(Const(\"(\", input2), ([_1, input3]) => If2(ParameterList(input3), ([_2, input4]) => If2(Const(\")\", input4), ([_3, input5]) => If2(Const(\"=>\", input5), ([_4, input6]) => If2(Type(input6), ([_5, input7]) => [[_0, _1, _2, _3, _4, _5], input7])))))), ([_0, input2]) => [_Constructor_Mapping(_0), input2]);\n var MappedReadonly = (input) => If2(If2(If2(Const(\"+\", input), ([_0, input2]) => If2(Const(\"readonly\", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(Const(\"-\", input), ([_0, input2]) => If2(Const(\"readonly\", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(Const(\"readonly\", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])))), ([_0, input2]) => [MappedReadonlyMapping(_0), input2]);\n var MappedOptional = (input) => If2(If2(If2(Const(\"+\", input), ([_0, input2]) => If2(Const(\"?\", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(Const(\"-\", input), ([_0, input2]) => If2(Const(\"?\", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(Const(\"?\", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])))), ([_0, input2]) => [MappedOptionalMapping(_0), input2]);\n var MappedAs = (input) => If2(If2(If2(Const(\"as\", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [MappedAsMapping(_0), input2]);\n var _Mapped_ = (input) => If2(If2(Const(\"{\", input), ([_0, input2]) => If2(MappedReadonly(input2), ([_1, input3]) => If2(Const(\"[\", input3), ([_2, input4]) => If2(Ident(input4), ([_3, input5]) => If2(Const(\"in\", input5), ([_4, input6]) => If2(Type(input6), ([_5, input7]) => If2(MappedAs(input7), ([_6, input8]) => If2(Const(\"]\", input8), ([_7, input9]) => If2(MappedOptional(input9), ([_8, input10]) => If2(Const(\":\", input10), ([_9, input11]) => If2(Type(input11), ([_10, input12]) => If2(OptionalSemiColon(input12), ([_11, input13]) => If2(Const(\"}\", input13), ([_12, input14]) => [[_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12], input14]))))))))))))), ([_0, input2]) => [_Mapped_Mapping(_0), input2]);\n var Reference = (input) => If2(Ident(input), ([_0, input2]) => [ReferenceMapping(_0), input2]);\n var WithBigInt = (input) => If2(BigInt3(input), ([_0, input2]) => [WithBigIntMapping(_0), input2]);\n var WithNumber = (input) => If2(Number3(input), ([_0, input2]) => [WithNumberMapping(_0), input2]);\n var WithBoolean = (input) => If2(If2(Const(\"true\", input), ([_0, input2]) => [_0, input2], () => If2(Const(\"false\", input), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [WithBooleanMapping(_0), input2]);\n var WithString = (input) => If2(String3(['\"', \"'\"], input), ([_0, input2]) => [WithStringMapping(_0), input2]);\n var WithNull = (input) => If2(Const(\"null\", input), ([_0, input2]) => [WithNullMapping(_0), input2]);\n var WithUndefined = (input) => If2(Const(\"undefined\", input), ([_0, input2]) => [WithUndefinedMapping(_0), input2]);\n var WithProperty = (input) => If2(If2(PropertyKey(input), ([_0, input2]) => If2(Const(\":\", input2), ([_1, input3]) => If2(WithValue(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [WithPropertyMapping(_0), input2]);\n var WithPropertyList_0 = (input, result = []) => If2(If2(PropertyDelimiter(input), ([_0, input2]) => If2(WithProperty(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => WithPropertyList_0(input2, [...result, _0]), () => [result, input]);\n var WithPropertyList = (input) => If2(If2(If2(WithProperty(input), ([_0, input2]) => If2(WithPropertyList_0(input2), ([_1, input3]) => If2(If2(PropertyDelimiter(input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [WithPropertyListMapping(_0), input2]);\n var WithObject = (input) => If2(If2(Const(\"{\", input), ([_0, input2]) => If2(WithPropertyList(input2), ([_1, input3]) => If2(Const(\"}\", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [WithObjectMapping(_0), input2]);\n var WithElementList_0 = (input, result = []) => If2(If2(Const(\",\", input), ([_0, input2]) => If2(WithValue(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => WithElementList_0(input2, [...result, _0]), () => [result, input]);\n var WithElementList = (input) => If2(If2(If2(WithValue(input), ([_0, input2]) => If2(WithElementList_0(input2), ([_1, input3]) => If2(If2(Const(\",\", input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [WithElementListMapping(_0), input2]);\n var WithArray = (input) => If2(If2(Const(\"[\", input), ([_0, input2]) => If2(WithElementList(input2), ([_1, input3]) => If2(Const(\"]\", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [WithArrayMapping(_0), input2]);\n var WithValue = (input) => If2(If2(WithBigInt(input), ([_0, input2]) => [_0, input2], () => If2(WithNumber(input), ([_0, input2]) => [_0, input2], () => If2(WithBoolean(input), ([_0, input2]) => [_0, input2], () => If2(WithString(input), ([_0, input2]) => [_0, input2], () => If2(WithNull(input), ([_0, input2]) => [_0, input2], () => If2(WithUndefined(input), ([_0, input2]) => [_0, input2], () => If2(WithObject(input), ([_0, input2]) => [_0, input2], () => If2(WithArray(input), ([_0, input2]) => [_0, input2], () => [])))))))), ([_0, input2]) => [WithValueMapping(_0), input2]);\n var PatternBigInt = (input) => If2(Const(\"-?(?:0|[1-9][0-9]*)n\", input), ([_0, input2]) => [PatternBigIntMapping(_0), input2]);\n var PatternString = (input) => If2(Const(\".*\", input), ([_0, input2]) => [PatternStringMapping(_0), input2]);\n var PatternNumber = (input) => If2(Const(\"-?(?:0|[1-9][0-9]*)(?:\\\\.[0-9]+)?\", input), ([_0, input2]) => [PatternNumberMapping(_0), input2]);\n var PatternInteger = (input) => If2(Const(\"-?(?:0|[1-9][0-9]*)\", input), ([_0, input2]) => [PatternIntegerMapping(_0), input2]);\n var PatternNever = (input) => If2(Const(\"(?!)\", input), ([_0, input2]) => [PatternNeverMapping(_0), input2]);\n var PatternText = (input) => If2(Until_1([\"-?(?:0|[1-9][0-9]*)n\", \".*\", \"-?(?:0|[1-9][0-9]*)(?:\\\\.[0-9]+)?\", \"-?(?:0|[1-9][0-9]*)\", \"(?!)\", \"(\", \")\", \"$\", \"|\"], input), ([_0, input2]) => [PatternTextMapping(_0), input2]);\n var PatternBase = (input) => If2(If2(PatternBigInt(input), ([_0, input2]) => [_0, input2], () => If2(PatternString(input), ([_0, input2]) => [_0, input2], () => If2(PatternNumber(input), ([_0, input2]) => [_0, input2], () => If2(PatternInteger(input), ([_0, input2]) => [_0, input2], () => If2(PatternNever(input), ([_0, input2]) => [_0, input2], () => If2(PatternGroup(input), ([_0, input2]) => [_0, input2], () => If2(PatternText(input), ([_0, input2]) => [_0, input2], () => []))))))), ([_0, input2]) => [PatternBaseMapping(_0), input2]);\n var PatternGroup = (input) => If2(If2(Const(\"(\", input), ([_0, input2]) => If2(PatternBody(input2), ([_1, input3]) => If2(Const(\")\", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [PatternGroupMapping(_0), input2]);\n var PatternUnion = (input) => If2(If2(If2(PatternTerm(input), ([_0, input2]) => If2(Const(\"|\", input2), ([_1, input3]) => If2(PatternUnion(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2(If2(PatternTerm(input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => []))), ([_0, input2]) => [PatternUnionMapping(_0), input2]);\n var PatternTerm = (input) => If2(If2(PatternBase(input), ([_0, input2]) => If2(PatternBody(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [PatternTermMapping(_0), input2]);\n var PatternBody = (input) => If2(If2(PatternUnion(input), ([_0, input2]) => [_0, input2], () => If2(PatternTerm(input), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [PatternBodyMapping(_0), input2]);\n var Pattern = (input) => If2(If2(Const(\"^\", input), ([_0, input2]) => If2(PatternBody(input2), ([_1, input3]) => If2(Const(\"$\", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [PatternMapping(_0), input2]);\n var InterfaceDeclarationHeritageList_0 = (input, result = []) => If2(If2(Const(\",\", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => InterfaceDeclarationHeritageList_0(input2, [...result, _0]), () => [result, input]);\n var InterfaceDeclarationHeritageList = (input) => If2(If2(If2(Type(input), ([_0, input2]) => If2(InterfaceDeclarationHeritageList_0(input2), ([_1, input3]) => If2(If2(Const(\",\", input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [InterfaceDeclarationHeritageListMapping(_0), input2]);\n var InterfaceDeclarationHeritage = (input) => If2(If2(If2(Const(\"extends\", input), ([_0, input2]) => If2(InterfaceDeclarationHeritageList(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [InterfaceDeclarationHeritageMapping(_0), input2]);\n var InterfaceDeclarationGeneric = (input) => If2(If2(Const(\"interface\", input), ([_0, input2]) => If2(Ident(input2), ([_1, input3]) => If2(GenericParameters(input3), ([_2, input4]) => If2(InterfaceDeclarationHeritage(input4), ([_3, input5]) => If2(Properties(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [InterfaceDeclarationGenericMapping(_0), input2]);\n var InterfaceDeclaration = (input) => If2(If2(Const(\"interface\", input), ([_0, input2]) => If2(Ident(input2), ([_1, input3]) => If2(InterfaceDeclarationHeritage(input3), ([_2, input4]) => If2(Properties(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [InterfaceDeclarationMapping(_0), input2]);\n var TypeAliasDeclarationGeneric = (input) => If2(If2(Const(\"type\", input), ([_0, input2]) => If2(Ident(input2), ([_1, input3]) => If2(GenericParameters(input3), ([_2, input4]) => If2(Const(\"=\", input4), ([_3, input5]) => If2(Type(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [TypeAliasDeclarationGenericMapping(_0), input2]);\n var TypeAliasDeclaration = (input) => If2(If2(Const(\"type\", input), ([_0, input2]) => If2(Ident(input2), ([_1, input3]) => If2(Const(\"=\", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [TypeAliasDeclarationMapping(_0), input2]);\n var ExportKeyword = (input) => If2(If2(If2(Const(\"export\", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ExportKeywordMapping(_0), input2]);\n var ModuleDeclarationDelimiter = (input) => If2(If2(If2(Const(\";\", input), ([_0, input2]) => If2(Const(\"\\n\", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(Const(\";\", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2(If2(Const(\"\\n\", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => []))), ([_0, input2]) => [ModuleDeclarationDelimiterMapping(_0), input2]);\n var ModuleDeclarationList_0 = (input, result = []) => If2(If2(ModuleDeclarationDelimiter(input), ([_0, input2]) => If2(ModuleDeclaration(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => ModuleDeclarationList_0(input2, [...result, _0]), () => [result, input]);\n var ModuleDeclarationList = (input) => If2(If2(If2(ModuleDeclaration(input), ([_0, input2]) => If2(ModuleDeclarationList_0(input2), ([_1, input3]) => If2(If2(ModuleDeclarationDelimiter(input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ModuleDeclarationListMapping(_0), input2]);\n var ModuleDeclaration = (input) => If2(If2(ExportKeyword(input), ([_0, input2]) => If2(If2(InterfaceDeclarationGeneric(input2), ([_02, input3]) => [_02, input3], () => If2(InterfaceDeclaration(input2), ([_02, input3]) => [_02, input3], () => If2(TypeAliasDeclarationGeneric(input2), ([_02, input3]) => [_02, input3], () => If2(TypeAliasDeclaration(input2), ([_02, input3]) => [_02, input3], () => [])))), ([_1, input3]) => If2(OptionalSemiColon(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [ModuleDeclarationMapping(_0), input2]);\n var Module = (input) => If2(If2(ModuleDeclaration(input), ([_0, input2]) => If2(ModuleDeclarationList(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [ModuleMapping(_0), input2]);\n var Script = (input) => If2(If2(Module(input), ([_0, input2]) => [_0, input2], () => If2(GenericType(input), ([_0, input2]) => [_0, input2], () => If2(Type(input), ([_0, input2]) => [_0, input2], () => []))), ([_0, input2]) => [ScriptMapping(_0), input2]);\n\n // node_modules/typebox/build/type/engine/patterns/template.mjs\n function ParseTemplateIntoTypes(template) {\n const parsed = TemplateLiteralTypes(`\\`${template}\\``);\n const result = guard_exports.IsEqual(parsed.length, 2) ? parsed[0] : Unreachable();\n return result;\n }\n\n // node_modules/typebox/build/type/engine/template_literal/encode.mjs\n function JoinString(input) {\n return input.join(\"|\");\n }\n function UnwrapTemplateLiteralPattern(pattern) {\n return pattern.slice(1, pattern.length - 1);\n }\n function EncodeLiteral(value, right, pattern) {\n return EncodeTypes(right, `${pattern}${value}`);\n }\n function EncodeBigInt(right, pattern) {\n return EncodeTypes(right, `${pattern}${BigIntPattern}`);\n }\n function EncodeInteger(right, pattern) {\n return EncodeTypes(right, `${pattern}${IntegerPattern}`);\n }\n function EncodeNumber(right, pattern) {\n return EncodeTypes(right, `${pattern}${NumberPattern}`);\n }\n function EncodeBoolean(right, pattern) {\n return EncodeType(Union([Literal(\"false\"), Literal(\"true\")]), right, pattern);\n }\n function EncodeString(right, pattern) {\n return EncodeTypes(right, `${pattern}${StringPattern}`);\n }\n function EncodeTemplateLiteral(templatePattern, right, pattern) {\n return EncodeTypes(right, `${pattern}${UnwrapTemplateLiteralPattern(templatePattern)}`);\n }\n function EncodeTemplateLiteralDeferred(types, right, pattern) {\n const templateLiteral = TemplateLiteralAction(types, {});\n const result = EncodeType(templateLiteral, right, pattern);\n return result;\n }\n function EncodeEnum(values, right, pattern) {\n const evaluated = EvaluateEnum(values);\n return EncodeType(evaluated, right, pattern);\n }\n function EncodeUnion(types, right, pattern, result = []) {\n return guard_exports.ShiftLeft(types, (head, tail) => EncodeUnion(tail, right, pattern, [...result, EncodeType(head, [], \"\")]), () => EncodeTypes(right, `${pattern}(${JoinString(result)})`));\n }\n function EncodeType(type, right, pattern) {\n return IsEnum2(type) ? EncodeEnum(type.enum, right, pattern) : IsInteger3(type) ? EncodeInteger(right, pattern) : IsLiteral(type) ? EncodeLiteral(type.const, right, pattern) : IsBigInt3(type) ? EncodeBigInt(right, pattern) : IsBoolean4(type) ? EncodeBoolean(right, pattern) : IsNumber4(type) ? EncodeNumber(right, pattern) : IsString4(type) ? EncodeString(right, pattern) : IsTemplateLiteral(type) ? EncodeTemplateLiteral(type.pattern, right, pattern) : IsTemplateLiteralDeferred(type) ? EncodeTemplateLiteralDeferred(type.parameters[0], right, pattern) : IsUnion(type) ? EncodeUnion(type.anyOf, right, pattern) : NeverPattern;\n }\n function EncodeTypes(types, pattern) {\n return guard_exports.ShiftLeft(types, (left, right) => EncodeType(left, right, pattern), () => pattern);\n }\n function EncodePattern(types) {\n const encoded = EncodeTypes(types, \"\");\n const result = `^${encoded}$`;\n return result;\n }\n function TemplateLiteralEncode(types) {\n const pattern = EncodePattern(types);\n const result = TemplateLiteralCreate(pattern);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/template_literal/instantiate.mjs\n function TemplateLiteralAction(types, options) {\n const result = CanInstantiate(types) ? memory_exports.Update(TemplateLiteralEncode(types), {}, options) : TemplateLiteralDeferred(types, options);\n return result;\n }\n function TemplateLiteralInstantiate(context2, state2, types, options) {\n const instantiatedTypes = InstantiateTypes(context2, state2, types);\n return TemplateLiteralAction(instantiatedTypes, options);\n }\n\n // node_modules/typebox/build/type/types/template_literal.mjs\n function TemplateLiteralDeferred(types, options = {}) {\n return Deferred(\"TemplateLiteral\", [types], options);\n }\n function IsTemplateLiteralDeferred(value) {\n return IsSchema2(value) && guard_exports.HasPropertyKey(value, \"action\") && guard_exports.IsEqual(value.action, \"TemplateLiteral\");\n }\n function TemplateLiteralFromTypes(types) {\n return TemplateLiteralAction(types, {});\n }\n function TemplateLiteralFromString(template) {\n const types = ParseTemplateIntoTypes(template);\n return TemplateLiteralFromTypes(types);\n }\n function TemplateLiteral2(input, options = {}) {\n const type = guard_exports.IsString(input) ? TemplateLiteralFromString(input) : TemplateLiteralFromTypes(input);\n return memory_exports.Update(type, {}, options);\n }\n function IsTemplateLiteral(value) {\n return IsKind(value, \"TemplateLiteral\");\n }\n\n // node_modules/typebox/build/type/extends/result.mjs\n var result_exports = {};\n __export(result_exports, {\n ExtendsFalse: () => ExtendsFalse,\n ExtendsTrue: () => ExtendsTrue,\n ExtendsUnion: () => ExtendsUnion,\n IsExtendsFalse: () => IsExtendsFalse,\n IsExtendsTrue: () => IsExtendsTrue,\n IsExtendsTrueLike: () => IsExtendsTrueLike,\n IsExtendsUnion: () => IsExtendsUnion,\n Match: () => Match4\n });\n function ExtendsUnion(inferred) {\n return memory_exports.Create({ [\"~kind\"]: \"ExtendsUnion\" }, { inferred });\n }\n function IsExtendsUnion(value) {\n return guard_exports.IsObject(value) && guard_exports.HasPropertyKey(value, \"~kind\") && guard_exports.HasPropertyKey(value, \"inferred\") && guard_exports.IsEqual(value[\"~kind\"], \"ExtendsUnion\") && guard_exports.IsObject(value.inferred);\n }\n function ExtendsTrue(inferred) {\n return memory_exports.Create({ [\"~kind\"]: \"ExtendsTrue\" }, { inferred });\n }\n function IsExtendsTrue(value) {\n return guard_exports.IsObject(value) && guard_exports.HasPropertyKey(value, \"~kind\") && guard_exports.HasPropertyKey(value, \"inferred\") && guard_exports.IsEqual(value[\"~kind\"], \"ExtendsTrue\") && guard_exports.IsObject(value.inferred);\n }\n function ExtendsFalse() {\n return memory_exports.Create({ [\"~kind\"]: \"ExtendsFalse\" }, {});\n }\n function IsExtendsFalse(value) {\n return guard_exports.IsObject(value) && guard_exports.HasPropertyKey(value, \"~kind\") && guard_exports.IsEqual(value[\"~kind\"], \"ExtendsFalse\");\n }\n function IsExtendsTrueLike(value) {\n return IsExtendsUnion(value) || IsExtendsTrue(value);\n }\n function Match4(result, true_, false_) {\n return IsExtendsTrueLike(result) ? true_(result.inferred) : false_();\n }\n\n // node_modules/typebox/build/type/extends/extends_right.mjs\n function ExtendsRightInfer(inferred, name, left, right) {\n return Match4(ExtendsLeft(inferred, left, right), (checkInferred) => ExtendsTrue(memory_exports.Assign(memory_exports.Assign(inferred, checkInferred), { [name]: left })), () => ExtendsFalse());\n }\n function ExtendsRightAny(inferred, _left) {\n return ExtendsTrue(inferred);\n }\n function ExtendsRightDependent(inferred, left, if_, then_, else_) {\n return Match4(ExtendsLeft(inferred, left, if_), (inferred2) => Match4(ExtendsLeft(inferred2, left, then_), (inferred3) => ExtendsTrue(inferred3), () => ExtendsFalse()), () => Match4(ExtendsLeft(inferred, left, else_), (inferred2) => ExtendsTrue(inferred2), () => ExtendsFalse()));\n }\n function ExtendsRightEnum(inferred, left, right) {\n const evaluated = EvaluateEnum(right);\n return ExtendsLeft(inferred, left, evaluated);\n }\n function ExtendsRightIntersect(inferred, left, right) {\n return guard_exports.ShiftLeft(right, (head, tail) => Match4(ExtendsLeft(inferred, left, head), (inferred2) => ExtendsRightIntersect(inferred2, left, tail), () => ExtendsFalse()), () => ExtendsTrue(inferred));\n }\n function ExtendsRightTemplateLiteral(inferred, left, right) {\n const evaluated = EvaluateTemplateLiteral(right);\n return ExtendsLeft(inferred, left, evaluated);\n }\n function ExtendsRightUnion(inferred, left, right) {\n return guard_exports.ShiftLeft(right, (head, tail) => Match4(ExtendsLeft(inferred, left, head), (inferred2) => ExtendsTrue(inferred2), () => ExtendsRightUnion(inferred, left, tail)), () => ExtendsFalse());\n }\n function ExtendsRight(inferred, left, right) {\n return IsAny(right) ? ExtendsRightAny(inferred, left) : IsDependent(right) ? ExtendsRightDependent(inferred, left, right.if, right.then, right.else) : IsEnum2(right) ? ExtendsRightEnum(inferred, left, right.enum) : IsInfer(right) ? ExtendsRightInfer(inferred, right.name, left, right.extends) : IsIntersect(right) ? ExtendsRightIntersect(inferred, left, right.allOf) : IsTemplateLiteral(right) ? ExtendsRightTemplateLiteral(inferred, left, right.pattern) : IsUnion(right) ? ExtendsRightUnion(inferred, left, right.anyOf) : IsUnknown(right) ? ExtendsTrue(inferred) : ExtendsFalse();\n }\n\n // node_modules/typebox/build/type/extends/any.mjs\n function ExtendsAny(inferred, left, right) {\n return IsInfer(right) ? ExtendsRight(inferred, left, right) : IsAny(right) ? ExtendsTrue(inferred) : IsUnknown(right) ? ExtendsTrue(inferred) : ExtendsUnion(inferred);\n }\n\n // node_modules/typebox/build/type/extends/array.mjs\n function ExtendsImmutable(left, right) {\n const isImmutableLeft = IsImmutable(left);\n const isImmutableRight = IsImmutable(right);\n return isImmutableLeft && isImmutableRight ? true : !isImmutableLeft && isImmutableRight ? true : isImmutableLeft && !isImmutableRight ? false : true;\n }\n function ExtendsArray(inferred, arrayLeft, left, right) {\n return IsArray3(right) ? ExtendsImmutable(arrayLeft, right) ? ExtendsLeft(inferred, left, right.items) : ExtendsFalse() : ExtendsRight(inferred, arrayLeft, right);\n }\n\n // node_modules/typebox/build/type/extends/bigint.mjs\n function ExtendsBigInt(inferred, left, right) {\n return IsBigInt3(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);\n }\n\n // node_modules/typebox/build/type/extends/boolean.mjs\n function ExtendsBoolean(inferred, left, right) {\n return IsBoolean4(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);\n }\n\n // node_modules/typebox/build/type/extends/parameters.mjs\n function ParameterCompare(inferred, left, leftRest, right, rightRest) {\n const checkLeft = IsInfer(right) ? left : right;\n const checkRight = IsInfer(right) ? right : left;\n const isLeftOptional = IsOptional(left);\n const isRightOptional = IsOptional(right);\n return !isLeftOptional && isRightOptional ? ExtendsFalse() : Match4(ExtendsLeft(inferred, checkLeft, checkRight), (inferred2) => ExtendsParameters(inferred2, leftRest, rightRest), () => ExtendsFalse());\n }\n function ParameterRight(inferred, left, leftRest, rightRest) {\n return guard_exports.ShiftLeft(rightRest, (head, tail) => ParameterCompare(inferred, left, leftRest, head, tail), () => IsOptional(left) ? ExtendsTrue(inferred) : ExtendsFalse());\n }\n function ParametersLeft(inferred, left, rightRest) {\n return guard_exports.ShiftLeft(left, (head, tail) => ParameterRight(inferred, head, tail, rightRest), () => ExtendsTrue(inferred));\n }\n function ExtendsParameters(inferred, left, right) {\n return ParametersLeft(inferred, left, right);\n }\n\n // node_modules/typebox/build/type/extends/return_type.mjs\n function ExtendsReturnType(inferred, left, right) {\n return IsVoid(right) ? ExtendsTrue(inferred) : ExtendsLeft(inferred, left, right);\n }\n\n // node_modules/typebox/build/type/extends/constructor.mjs\n function ExtendsConstructor(inferred, parameters, returnType, right) {\n return IsAny(right) ? ExtendsTrue(inferred) : IsUnknown(right) ? ExtendsTrue(inferred) : IsConstructor3(right) ? Match4(ExtendsParameters(inferred, parameters, right[\"parameters\"]), (inferred2) => ExtendsReturnType(inferred2, returnType, right[\"instanceType\"]), () => ExtendsFalse()) : ExtendsFalse();\n }\n\n // node_modules/typebox/build/type/extends/dependent.mjs\n function ExtendsDependent(inferred, if_, then_, else_, right) {\n return Match4(ExtendsLeft(inferred, if_, right), () => ExtendsLeft(inferred, then_, right), () => ExtendsLeft(inferred, else_, right));\n }\n\n // node_modules/typebox/build/type/extends/enum.mjs\n function ExtendsEnum(inferred, left, right) {\n const evaluated = EvaluateEnum(left);\n return ExtendsLeft(inferred, evaluated, right);\n }\n\n // node_modules/typebox/build/type/extends/function.mjs\n function ExtendsFunction(inferred, parameters, returnType, right) {\n return IsAny(right) ? ExtendsTrue(inferred) : IsUnknown(right) ? ExtendsTrue(inferred) : IsFunction3(right) ? Match4(ExtendsParameters(inferred, parameters, right[\"parameters\"]), (inferred2) => ExtendsReturnType(inferred2, returnType, right[\"returnType\"]), () => ExtendsFalse()) : ExtendsFalse();\n }\n\n // node_modules/typebox/build/type/extends/integer.mjs\n function ExtendsInteger(inferred, left, right) {\n return IsInteger3(right) ? ExtendsTrue(inferred) : IsNumber4(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);\n }\n\n // node_modules/typebox/build/type/extends/intersect.mjs\n function ExtendsIntersect(inferred, left, right) {\n const evaluated = EvaluateIntersect(left);\n return ExtendsLeft(inferred, evaluated, right);\n }\n\n // node_modules/typebox/build/type/extends/literal.mjs\n function ExtendsLiteralValue(inferred, left, right) {\n return left === right ? ExtendsTrue(inferred) : ExtendsFalse();\n }\n function ExtendsLiteralBigInt(inferred, left, right) {\n return IsLiteral(right) ? ExtendsLiteralValue(inferred, left, right.const) : IsBigInt3(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, Literal(left), right);\n }\n function ExtendsLiteralBoolean(inferred, left, right) {\n return IsLiteral(right) ? ExtendsLiteralValue(inferred, left, right.const) : IsBoolean4(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, Literal(left), right);\n }\n function ExtendsLiteralNumber(inferred, left, right) {\n return IsLiteral(right) ? ExtendsLiteralValue(inferred, left, right.const) : IsNumber4(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, Literal(left), right);\n }\n function ExtendsLiteralString(inferred, left, right) {\n return IsLiteral(right) ? ExtendsLiteralValue(inferred, left, right.const) : IsString4(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, Literal(left), right);\n }\n function ExtendsLiteral(inferred, left, right) {\n return guard_exports.IsBigInt(left.const) ? ExtendsLiteralBigInt(inferred, left.const, right) : guard_exports.IsBoolean(left.const) ? ExtendsLiteralBoolean(inferred, left.const, right) : guard_exports.IsNumber(left.const) ? ExtendsLiteralNumber(inferred, left.const, right) : guard_exports.IsString(left.const) ? ExtendsLiteralString(inferred, left.const, right) : Unreachable();\n }\n\n // node_modules/typebox/build/type/extends/never.mjs\n function ExtendsNever(inferred, left, right) {\n return IsInfer(right) ? ExtendsRight(inferred, left, right) : ExtendsTrue(inferred);\n }\n\n // node_modules/typebox/build/type/extends/null.mjs\n function ExtendsNull(inferred, left, right) {\n return IsNull3(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);\n }\n\n // node_modules/typebox/build/type/extends/number.mjs\n function ExtendsNumber(inferred, left, right) {\n return IsNumber4(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);\n }\n\n // node_modules/typebox/build/type/extends/object.mjs\n function ExtendsPropertyOptional(inferred, left, right) {\n return IsOptional(left) ? IsOptional(right) ? ExtendsTrue(inferred) : ExtendsFalse() : ExtendsTrue(inferred);\n }\n function ExtendsProperty(inferred, left, right) {\n return (\n // Right TInfer<TNever> is TExtendsFalse\n IsInfer(right) && IsNever(right.extends) ? ExtendsFalse() : Match4(ExtendsLeft(inferred, left, right), (inferred2) => ExtendsPropertyOptional(inferred2, left, right), () => ExtendsFalse())\n );\n }\n function ExtractInferredProperties(keys, properties) {\n return keys.reduce((result, key) => {\n return key in properties ? IsExtendsTrueLike(properties[key]) ? { ...result, ...properties[key].inferred } : Unreachable() : Unreachable();\n }, {});\n }\n function ExtendsPropertiesComparer(inferred, left, right) {\n const properties = {};\n for (const rightKey of guard_exports.Keys(right)) {\n properties[rightKey] = rightKey in left ? ExtendsProperty({}, left[rightKey], right[rightKey]) : IsOptional(right[rightKey]) ? IsInfer(right[rightKey]) ? ExtendsTrue(memory_exports.Assign(inferred, { [right[rightKey].name]: right[rightKey].extends })) : ExtendsTrue(inferred) : ExtendsFalse();\n }\n const checked = guard_exports.Values(properties).every((result) => IsExtendsTrueLike(result));\n const extracted = checked ? ExtractInferredProperties(guard_exports.Keys(properties), properties) : {};\n return checked ? ExtendsTrue(extracted) : ExtendsFalse();\n }\n function ExtendsProperties(inferred, left, right) {\n const compared = ExtendsPropertiesComparer(inferred, left, right);\n return IsExtendsTrueLike(compared) ? ExtendsTrue(memory_exports.Assign(inferred, compared.inferred)) : ExtendsFalse();\n }\n function ExtendsObjectToObject(inferred, left, right) {\n return ExtendsProperties(inferred, left, right);\n }\n function RecordMergeInferred(left, right) {\n return guard_exports.Keys(right).reduce((result, key) => {\n return {\n ...result,\n [key]: guard_exports.HasPropertyKey(left, key) ? IsUnion(result[key]) ? Union([...result[key].anyOf, right[key]]) : Union([left[key], right[key]]) : right[key]\n };\n }, left);\n }\n function ExtendsRecordComparer(properties, keys, type, result) {\n return guard_exports.ShiftLeft(keys, (left, right) => Match4(ExtendsLeft({}, properties[left], type), (inferred) => ExtendsRecordComparer(properties, right, type, RecordMergeInferred(result, inferred)), () => ExtendsFalse()), () => ExtendsTrue(result));\n }\n function ExtendsObjectToRecord(inferred, properties, _pattern, value) {\n const keys = guard_exports.Keys(properties);\n const result = ExtendsRecordComparer(properties, keys, value, inferred);\n return result;\n }\n function ExtendsObject(inferred, left, right) {\n return IsRecord(right) ? ExtendsObjectToRecord(inferred, left, RecordPattern(right), RecordValue(right)) : IsObject3(right) ? ExtendsObjectToObject(inferred, left, right.properties) : ExtendsRight(inferred, _Object_(left), right);\n }\n\n // node_modules/typebox/build/type/extends/record.mjs\n function FromObject4(inferred, properties) {\n return guard_exports.IsEqual(guard_exports.Keys(properties).length, 0) ? ExtendsTrue(inferred) : ExtendsFalse();\n }\n function FromRecord(inferred, _leftKey, leftValue, _rightKey, rightValue) {\n return ExtendsLeft(inferred, leftValue, rightValue);\n }\n function ExtendsRecord(inferred, leftPattern, leftValue, right) {\n return IsRecord(right) ? FromRecord(inferred, RecordPatternToType(leftPattern), leftValue, RecordPatternToType(RecordPattern(right)), RecordValue(right)) : IsObject3(right) ? FromObject4(inferred, right.properties) : IsAny(right) ? ExtendsTrue(inferred) : IsUnknown(right) ? ExtendsTrue(inferred) : ExtendsFalse();\n }\n\n // node_modules/typebox/build/type/extends/string.mjs\n function ExtendsString(inferred, left, right) {\n return IsString4(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);\n }\n\n // node_modules/typebox/build/type/extends/symbol.mjs\n function ExtendsSymbol(inferred, left, right) {\n return IsSymbol3(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);\n }\n\n // node_modules/typebox/build/type/extends/template_literal.mjs\n function ExtendsTemplateLiteral(inferred, left, right) {\n const evaluated = EvaluateTemplateLiteral(left);\n return ExtendsLeft(inferred, evaluated, right);\n }\n\n // node_modules/typebox/build/type/extends/inference.mjs\n function Inferrable(name, type) {\n return memory_exports.Create({ \"~kind\": \"Inferrable\" }, { name, type }, {});\n }\n function IsInferable(value) {\n return guard_exports.IsObject(value) && guard_exports.HasPropertyKey(value, \"~kind\") && guard_exports.HasPropertyKey(value, \"name\") && guard_exports.HasPropertyKey(value, \"type\") && guard_exports.IsEqual(value[\"~kind\"], \"Inferrable\") && guard_exports.IsString(value.name) && guard_exports.IsObject(value.type);\n }\n function TryRestInferable(type) {\n return IsRest(type) ? IsInfer(type.items) ? IsArray3(type.items.extends) ? Inferrable(type.items.name, type.items.extends.items) : IsUnknown(type.items.extends) ? Inferrable(type.items.name, type.items.extends) : void 0 : Unreachable() : void 0;\n }\n function TryInferable(type) {\n return IsInfer(type) ? Inferrable(type.name, type.extends) : void 0;\n }\n function TryInferResults(rest, right, result = []) {\n return guard_exports.ShiftLeft(rest, (head, tail) => Match4(ExtendsLeft({}, head, right), () => TryInferResults(tail, right, [...result, head]), () => void 0), () => result);\n }\n function InferTupleResult(inferred, name, left, right) {\n const results = TryInferResults(left, right);\n return guard_exports.IsArray(results) ? ExtendsTrue(memory_exports.Assign(inferred, { [name]: Tuple(results) })) : ExtendsFalse();\n }\n function InferUnionResult(inferred, name, left, right) {\n const results = TryInferResults(left, right);\n return guard_exports.IsArray(results) ? ExtendsTrue(memory_exports.Assign(inferred, { [name]: Union(results) })) : ExtendsFalse();\n }\n\n // node_modules/typebox/build/type/extends/tuple.mjs\n function Reverse(types) {\n return [...types].reverse();\n }\n function ApplyReverse(types, reversed) {\n return reversed ? Reverse(types) : types;\n }\n function Reversed(types) {\n const first = types.length > 0 ? types[0] : void 0;\n const inferrable = IsSchema2(first) ? TryRestInferable(first) : void 0;\n return IsSchema2(inferrable);\n }\n function ElementsCompare(inferred, reversed, left, leftRest, right, rightRest) {\n return Match4(ExtendsLeft(inferred, left, right), (checkInferred) => Elements(checkInferred, reversed, leftRest, rightRest), () => ExtendsFalse());\n }\n function ElementsLeft(inferred, reversed, leftRest, right, rightRest) {\n const inferable = TryRestInferable(right);\n return (\n // Rest Inferrable Right Means we delegate to TInferTupleResult to Generate a Result\n IsInferable(inferable) ? InferTupleResult(inferred, inferable[\"name\"], ApplyReverse(leftRest, reversed), inferable[\"type\"]) : guard_exports.ShiftLeft(leftRest, (head, tail) => ElementsCompare(inferred, reversed, head, tail, right, rightRest), () => ExtendsFalse())\n );\n }\n function ElementsRight(inferred, reversed, leftRest, rightRest) {\n return guard_exports.ShiftLeft(rightRest, (head, tail) => ElementsLeft(inferred, reversed, leftRest, head, tail), () => guard_exports.IsEqual(leftRest.length, 0) ? ExtendsTrue(inferred) : ExtendsFalse());\n }\n function Elements(inferred, reversed, leftRest, rightRest) {\n return ElementsRight(inferred, reversed, leftRest, rightRest);\n }\n function ExtendsTupleToTuple(inferred, left, right) {\n const instantiatedRight = InstantiateElements(inferred, State([], []), right);\n const reversed = Reversed(instantiatedRight);\n return Elements(inferred, reversed, ApplyReverse(left, reversed), ApplyReverse(instantiatedRight, reversed));\n }\n function ExtendsTupleToArray(inferred, left, right) {\n const inferrable = TryInferable(right);\n return IsInferable(inferrable) ? InferUnionResult(inferred, inferrable[\"name\"], left, inferrable[\"type\"]) : guard_exports.ShiftLeft(left, (head, tail) => Match4(ExtendsLeft(inferred, head, right), (inferred2) => ExtendsTupleToArray(inferred2, tail, right), () => ExtendsFalse()), () => ExtendsTrue(inferred));\n }\n function ExtendsTuple(inferred, left, right) {\n const instantiatedLeft = InstantiateElements(inferred, State([], []), left);\n return IsTuple(right) ? ExtendsTupleToTuple(inferred, instantiatedLeft, right.items) : IsArray3(right) ? ExtendsTupleToArray(inferred, instantiatedLeft, right.items) : ExtendsRight(inferred, Tuple(instantiatedLeft), right);\n }\n\n // node_modules/typebox/build/type/extends/undefined.mjs\n function ExtendsUndefined(inferred, left, right) {\n return IsVoid(right) ? ExtendsTrue(inferred) : IsUndefined3(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);\n }\n\n // node_modules/typebox/build/type/extends/union.mjs\n function ExtendsUnionSome(inferred, type, unionTypes) {\n return guard_exports.ShiftLeft(unionTypes, (head, tail) => Match4(ExtendsLeft(inferred, type, head), (inferred2) => ExtendsTrue(inferred2), () => ExtendsUnionSome(inferred, type, tail)), () => ExtendsFalse());\n }\n function ExtendsUnionLeft(inferred, left, right) {\n return guard_exports.ShiftLeft(left, (head, tail) => Match4(ExtendsUnionSome(inferred, head, right), (inferred2) => ExtendsUnionLeft(inferred2, tail, right), () => ExtendsFalse()), () => ExtendsTrue(inferred));\n }\n function ExtendsUnion2(inferred, left, right) {\n const inferrable = TryInferable(right);\n return IsInferable(inferrable) ? InferUnionResult(inferred, inferrable.name, left, inferrable.type) : IsUnion(right) ? ExtendsUnionLeft(inferred, left, right.anyOf) : ExtendsUnionLeft(inferred, left, [right]);\n }\n\n // node_modules/typebox/build/type/extends/unknown.mjs\n function ExtendsUnknown(inferred, left, right) {\n return IsInfer(right) ? ExtendsRight(inferred, left, right) : IsAny(right) ? ExtendsTrue(inferred) : IsUnknown(right) ? ExtendsTrue(inferred) : ExtendsFalse();\n }\n\n // node_modules/typebox/build/type/extends/void.mjs\n function ExtendsVoid(inferred, left, right) {\n return IsVoid(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);\n }\n\n // node_modules/typebox/build/type/extends/extends_left.mjs\n function ExtendsLeft(inferred, left, right) {\n return IsAny(left) ? ExtendsAny(inferred, left, right) : IsArray3(left) ? ExtendsArray(inferred, left, left.items, right) : IsBigInt3(left) ? ExtendsBigInt(inferred, left, right) : IsBoolean4(left) ? ExtendsBoolean(inferred, left, right) : IsConstructor3(left) ? ExtendsConstructor(inferred, left.parameters, left.instanceType, right) : IsDependent(left) ? ExtendsDependent(inferred, left.if, left.then, left.else, right) : IsEnum2(left) ? ExtendsEnum(inferred, left.enum, right) : IsFunction3(left) ? ExtendsFunction(inferred, left.parameters, left.returnType, right) : IsInteger3(left) ? ExtendsInteger(inferred, left, right) : IsIntersect(left) ? ExtendsIntersect(inferred, left.allOf, right) : IsLiteral(left) ? ExtendsLiteral(inferred, left, right) : IsNever(left) ? ExtendsNever(inferred, left, right) : IsNull3(left) ? ExtendsNull(inferred, left, right) : IsNumber4(left) ? ExtendsNumber(inferred, left, right) : IsObject3(left) ? ExtendsObject(inferred, left.properties, right) : IsRecord(left) ? ExtendsRecord(inferred, RecordPattern(left), RecordValue(left), right) : IsString4(left) ? ExtendsString(inferred, left, right) : IsSymbol3(left) ? ExtendsSymbol(inferred, left, right) : IsTemplateLiteral(left) ? ExtendsTemplateLiteral(inferred, left.pattern, right) : IsTuple(left) ? ExtendsTuple(inferred, left.items, right) : IsUndefined3(left) ? ExtendsUndefined(inferred, left, right) : IsUnion(left) ? ExtendsUnion2(inferred, left.anyOf, right) : IsUnknown(left) ? ExtendsUnknown(inferred, left, right) : IsVoid(left) ? ExtendsVoid(inferred, left, right) : ExtendsFalse();\n }\n\n // node_modules/typebox/build/type/engine/interface/instantiate.mjs\n function InterfaceOperation(heritage, properties) {\n const result = EvaluateIntersect([...heritage, _Object_(properties)]);\n return result;\n }\n function InterfaceAction(heritage, properties, options) {\n const result = CanInstantiate(heritage) ? memory_exports.Update(InterfaceOperation(heritage, properties), {}, options) : InterfaceDeferred(heritage, properties, options);\n return result;\n }\n function InterfaceInstantiate(context2, state2, heritage, properties, options) {\n const instantiatedHeritage = InstantiateTypes(context2, state2, heritage);\n const instantiatedProperties = InstantiateProperties(context2, state2, properties);\n return InterfaceAction(instantiatedHeritage, instantiatedProperties, options);\n }\n\n // node_modules/typebox/build/type/action/interface.mjs\n function InterfaceDeferred(heritage, properties, options = {}) {\n return Deferred(\"Interface\", [heritage, properties], options);\n }\n function IsInterfaceDeferred(value) {\n return IsSchema2(value) && guard_exports.HasPropertyKey(value, \"action\") && guard_exports.IsEqual(value.action, \"Interface\");\n }\n function Interface(heritage, properties, options = {}) {\n return InterfaceAction(heritage, properties, options);\n }\n\n // node_modules/typebox/build/type/engine/cyclic/check.mjs\n function FromRef(stack, context2, ref) {\n return stack.includes(ref) ? true : FromType3([...stack, ref], context2, context2[ref]);\n }\n function FromProperties(stack, context2, properties) {\n const types = PropertyValues(properties);\n return FromTypes2(stack, context2, types);\n }\n function FromTypes2(stack, context2, types) {\n return guard_exports.ShiftLeft(types, (left, right) => FromType3(stack, context2, left) ? true : FromTypes2(stack, context2, right), () => false);\n }\n function FromType3(stack, context2, type) {\n return IsRef2(type) ? FromRef(stack, context2, type.$ref) : IsArray3(type) ? FromType3(stack, context2, type.items) : IsConstructor3(type) ? FromTypes2(stack, context2, [...type.parameters, type.instanceType]) : IsFunction3(type) ? FromTypes2(stack, context2, [...type.parameters, type.returnType]) : IsInterfaceDeferred(type) ? FromProperties(stack, context2, type.parameters[1]) : IsIntersect(type) ? FromTypes2(stack, context2, type.allOf) : IsObject3(type) ? FromProperties(stack, context2, type.properties) : IsUnion(type) ? FromTypes2(stack, context2, type.anyOf) : IsTuple(type) ? FromTypes2(stack, context2, type.items) : IsRecord(type) ? FromType3(stack, context2, RecordValue(type)) : false;\n }\n function CyclicCheck(stack, context2, type) {\n const result = FromType3(stack, context2, type);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/cyclic/candidates.mjs\n function ResolveCandidateKeys(context2, keys) {\n return keys.reduce((result, left) => {\n return CyclicCheck([left], context2, context2[left]) ? [...result, left] : result;\n }, []);\n }\n function CyclicCandidates(context2) {\n const keys = PropertyKeys(context2);\n const result = ResolveCandidateKeys(context2, keys);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/cyclic/dependencies.mjs\n function FromRef2(context2, ref, result) {\n return result.includes(ref) ? result : ref in context2 ? FromType4(context2, context2[ref], [...result, ref]) : Unreachable();\n }\n function FromProperties2(context2, properties, result) {\n const types = PropertyValues(properties);\n return FromTypes3(context2, types, result);\n }\n function FromTypes3(context2, types, result) {\n return types.reduce((result2, left) => {\n return FromType4(context2, left, result2);\n }, result);\n }\n function FromType4(context2, type, result) {\n return IsRef2(type) ? FromRef2(context2, type.$ref, result) : IsArray3(type) ? FromType4(context2, type.items, result) : IsConstructor3(type) ? FromTypes3(context2, [...type.parameters, type.instanceType], result) : IsFunction3(type) ? FromTypes3(context2, [...type.parameters, type.returnType], result) : IsInterfaceDeferred(type) ? FromProperties2(context2, type.parameters[1], result) : IsIntersect(type) ? FromTypes3(context2, type.allOf, result) : IsObject3(type) ? FromProperties2(context2, type.properties, result) : IsUnion(type) ? FromTypes3(context2, type.anyOf, result) : IsTuple(type) ? FromTypes3(context2, type.items, result) : IsRecord(type) ? FromType4(context2, RecordValue(type), result) : result;\n }\n function CyclicDependencies(context2, key, type) {\n const result = FromType4(context2, type, [key]);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/cyclic/extends.mjs\n function FromRef3(_ref) {\n return Any();\n }\n function FromProperties3(properties) {\n return guard_exports.Keys(properties).reduce((result, key) => {\n return { ...result, [key]: FromType5(properties[key]) };\n }, {});\n }\n function FromTypes4(types) {\n return types.reduce((result, left) => {\n return [...result, FromType5(left)];\n }, []);\n }\n function FromType5(type) {\n return IsRef2(type) ? FromRef3(type.$ref) : IsArray3(type) ? _Array_(FromType5(type.items), ArrayOptions(type)) : IsConstructor3(type) ? Constructor(FromTypes4(type.parameters), FromType5(type.instanceType)) : IsFunction3(type) ? _Function_(FromTypes4(type.parameters), FromType5(type.returnType)) : IsIntersect(type) ? Intersect(FromTypes4(type.allOf)) : IsObject3(type) ? _Object_(FromProperties3(type.properties)) : IsRecord(type) ? Record(RecordKey(type), FromType5(RecordValue(type))) : IsUnion(type) ? Union(FromTypes4(type.anyOf)) : IsTuple(type) ? Tuple(FromTypes4(type.items)) : type;\n }\n function CyclicAnyFromParameters(defs, ref) {\n return ref in defs ? FromType5(defs[ref]) : Unknown();\n }\n function CyclicExtends(type) {\n return CyclicAnyFromParameters(type.$defs, type.$ref);\n }\n\n // node_modules/typebox/build/type/engine/cyclic/instantiate.mjs\n function CyclicInterface(context2, heritage, properties) {\n const instantiatedHeritage = InstantiateTypes(context2, State([], []), heritage);\n const instantiatedProperties = InstantiateProperties({}, State([], []), properties);\n const evaluatedInterface = EvaluateIntersect([...instantiatedHeritage, _Object_(instantiatedProperties)]);\n return evaluatedInterface;\n }\n function CyclicDefinitions(context2, dependencies) {\n const keys = guard_exports.Keys(context2).filter((key) => dependencies.includes(key));\n return keys.reduce((result, key) => {\n const type = context2[key];\n const instantiatedType = IsInterfaceDeferred(type) ? CyclicInterface(context2, type.parameters[0], type.parameters[1]) : type;\n return { ...result, [key]: instantiatedType };\n }, {});\n }\n function InstantiateCyclic(context2, ref, type) {\n const dependencies = CyclicDependencies(context2, ref, type);\n const definitions = CyclicDefinitions(context2, dependencies);\n const result = Cyclic(definitions, ref);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/cyclic/target.mjs\n function Resolve(defs, ref) {\n return ref in defs ? IsRef2(defs[ref]) ? Resolve(defs, defs[ref].$ref) : defs[ref] : Never();\n }\n function CyclicTarget(defs, ref) {\n const result = Resolve(defs, ref);\n return result;\n }\n\n // node_modules/typebox/build/type/extends/extends.mjs\n function Canonical(type) {\n return IsCyclic(type) ? CyclicExtends(type) : IsUnsafe(type) ? Unknown() : type;\n }\n function Extends(inferred, left, right) {\n const canonicalLeft = Canonical(left);\n const canonicalRight = Canonical(right);\n return ExtendsLeft(inferred, canonicalLeft, canonicalRight);\n }\n\n // node_modules/typebox/build/type/engine/evaluate/compare.mjs\n var CompareResultEqual = 0;\n var CompareResultDisjoint = 1;\n var CompareResultLeftInside = 2;\n var CompareResultRightInside = 3;\n function Compare(left, right) {\n const extendsCheck = [Extends({}, left, right), Extends({}, right, left)];\n return result_exports.IsExtendsTrueLike(extendsCheck[0]) && result_exports.IsExtendsTrueLike(extendsCheck[1]) ? CompareResultEqual : result_exports.IsExtendsTrueLike(extendsCheck[0]) && result_exports.IsExtendsFalse(extendsCheck[1]) ? CompareResultLeftInside : result_exports.IsExtendsFalse(extendsCheck[0]) && result_exports.IsExtendsTrueLike(extendsCheck[1]) ? CompareResultRightInside : CompareResultDisjoint;\n }\n\n // node_modules/typebox/build/type/engine/evaluate/broaden.mjs\n function BroadenFilter(type, types, result = [], all = types) {\n return guard_exports.ShiftLeft(types, (left, right) => {\n const compare = Compare(type, left);\n return guard_exports.IsEqual(compare, CompareResultLeftInside) || guard_exports.IsEqual(compare, CompareResultEqual) ? all : guard_exports.IsEqual(compare, CompareResultDisjoint) ? BroadenFilter(type, right, [...result, left], all) : BroadenFilter(type, right, result, all);\n }, () => [...result, type]);\n }\n function BroadenType(type, types, result) {\n const evaluated = EvaluateType(type);\n return IsAny(evaluated) ? [evaluated] : (\n // terminate (always the most broad)\n IsUnknown(evaluated) ? [evaluated] : (\n // terminate (always the most broad)\n IsNever(evaluated) ? BroadenTypes(types, result) : (\n // ignored: never is dropped\n IsObject3(evaluated) ? BroadenTypes(types, [...result, evaluated]) : (\n // objects are always considered (too expensive to compare)\n BroadenTypes(types, BroadenFilter(evaluated, result))\n )\n )\n )\n );\n }\n function BroadenTypes(types, result = []) {\n return guard_exports.ShiftLeft(types, (left, right) => BroadenType(left, right, result), () => result);\n }\n function Broaden(types) {\n const broadened = BroadenTypes(types);\n const flattened = Flatten(broadened);\n return flattened;\n }\n\n // node_modules/typebox/build/type/engine/evaluate/instantiate.mjs\n function EvaluateAction(type, options) {\n const result = memory_exports.Update(EvaluateType(type), {}, options);\n return result;\n }\n function EvaluateInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return EvaluateAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/engine/call/distribute_arguments.mjs\n function CollectDistributionNames(expression, result = []) {\n return (\n // Conditional\n IsDeferred(expression) && guard_exports.IsEqual(expression.action, \"Conditional\") ? IsRef2(expression.parameters[0]) ? CollectDistributionNames(expression.parameters[2], CollectDistributionNames(expression.parameters[3], [...result, expression.parameters[0][\"$ref\"]])) : CollectDistributionNames(expression.parameters[2], CollectDistributionNames(expression.parameters[3], result)) : IsDeferred(expression) && guard_exports.IsEqual(expression.action, \"Mapped\") ? IsDeferred(expression.parameters[1]) && guard_exports.IsEqual(expression.parameters[1].action, \"KeyOf\") && IsRef2(expression.parameters[1].parameters[0]) ? [...result, expression.parameters[1].parameters[0][\"$ref\"]] : result : result\n );\n }\n function BuildDistributionArray(parameters, names3) {\n return parameters.reduce((result, left) => [...result, names3.includes(left.name)], []);\n }\n function ZipDistributionArray(arguments_, distributionArray, result = []) {\n return guard_exports.ShiftLeft(arguments_, (argumentLeft, argumentRight) => guard_exports.ShiftLeft(distributionArray, (booleanLeft, booleanRight) => ZipDistributionArray(argumentRight, booleanRight, [...result, [booleanLeft, argumentLeft]]), () => result), () => result);\n }\n function CanonicalArgument(type) {\n return IsTemplateLiteral(type) ? EvaluateTemplateLiteral(type.pattern) : IsEnum2(type) ? EvaluateEnum(type.enum) : type;\n }\n function Expand(type) {\n const canonicalArgument = CanonicalArgument(type);\n return IsUnion(canonicalArgument) ? [...canonicalArgument.anyOf] : [canonicalArgument];\n }\n function Append(current, type) {\n return current.reduce((result, left) => [...result, [...left, type]], []);\n }\n function Cross(current, variants) {\n return variants.reduce((result, left) => {\n return [...result, ...Append(current, left)];\n }, []);\n }\n function Distribute2(zipped) {\n return zipped.reduce((result, left) => {\n return guard_exports.IsEqual(left[0], true) ? Cross(result, Expand(left[1])) : Cross(result, [left[1]]);\n }, [[]]);\n }\n function DistributeArguments(parameters, arguments_, expression) {\n const distributionNames = CollectDistributionNames(expression);\n const distributionArray = BuildDistributionArray(parameters, distributionNames);\n const zippedArguments = ZipDistributionArray(arguments_, distributionArray);\n return IsDeferred(expression) && guard_exports.IsEqual(expression.action, \"Conditional\") ? Distribute2(zippedArguments) : IsDeferred(expression) && guard_exports.IsEqual(expression.action, \"Mapped\") ? Distribute2(zippedArguments) : [arguments_];\n }\n\n // node_modules/typebox/build/type/engine/call/resolve_target.mjs\n function FromNotResolvable() {\n return [\"(not-resolvable)\", Never()];\n }\n function FromNotGeneric() {\n return [\"(not-generic)\", Never()];\n }\n function FromGeneric(name, parameters, expression) {\n return [name, Generic(parameters, expression)];\n }\n function FromRef4(context2, ref, arguments_) {\n return ref in context2 ? FromType6(context2, ref, context2[ref], arguments_) : FromNotResolvable();\n }\n function FromType6(context2, name, target, arguments_) {\n return IsGeneric(target) ? FromGeneric(name, target.parameters, target.expression) : IsRef2(target) ? FromRef4(context2, target.$ref, arguments_) : FromNotGeneric();\n }\n function ResolveTarget(context2, target, arguments_) {\n return FromType6(context2, \"(anonymous)\", target, arguments_);\n }\n\n // node_modules/typebox/build/type/engine/call/resolve_arguments.mjs\n function AssertArgumentExtends(name, type, extends_) {\n if (IsInfer(type) || IsCall(type) || result_exports.IsExtendsTrueLike(Extends({}, type, extends_)))\n return;\n const cause = { parameter: name, expect: extends_, actual: type };\n throw new Error(`Argument for parameter ${name} does not satisfy constraint`, { cause });\n }\n function BindArgument(context2, state2, name, extends_, type) {\n const instantiatedArgument = InstantiateType(context2, state2, type);\n AssertArgumentExtends(name, instantiatedArgument, extends_);\n return memory_exports.Assign(context2, { [name]: instantiatedArgument });\n }\n function BindArguments(context2, state2, parameterLeft, parameterRight, arguments_) {\n const instantiatedExtends = InstantiateType(context2, state2, parameterLeft.extends);\n const instantiatedEquals = InstantiateType(context2, state2, parameterLeft.equals);\n return guard_exports.ShiftLeft(arguments_, (left, right) => BindParameters(BindArgument(context2, state2, parameterLeft[\"name\"], instantiatedExtends, left), state2, parameterRight, right), () => BindParameters(BindArgument(context2, state2, parameterLeft[\"name\"], instantiatedExtends, instantiatedEquals), state2, parameterRight, []));\n }\n function BindParameters(context2, state2, parameters, arguments_) {\n return guard_exports.ShiftLeft(parameters, (left, right) => BindArguments(context2, state2, left, right, arguments_), () => context2);\n }\n function ResolveArgumentsContext(context2, state2, parameters, arguments_) {\n return BindParameters(context2, state2, parameters, arguments_);\n }\n\n // node_modules/typebox/build/type/engine/call/instantiate.mjs\n var instantiationDepth = 0;\n var instantiationCount = 0;\n function InstantiationAssert() {\n if (guard_exports.IsLessThan(instantiationCount, settings_exports.Get().maxInstantiationCount))\n return;\n throw Error(\"Type instantiation is excessively deep and possibly infinite\");\n }\n function InstantiationIncrement() {\n InstantiationAssert();\n instantiationCount++;\n instantiationDepth++;\n }\n function InstantiationDecrement() {\n instantiationDepth--;\n if (guard_exports.IsEqual(instantiationDepth, 0))\n instantiationCount = 0;\n }\n function Peek(state2) {\n const result = guard_exports.IsGreaterThan(state2.callstack.length, 0) ? state2.callstack[state2.callstack.length - 1] : \"\";\n return result;\n }\n function IsTailCall(state2, name) {\n const result = guard_exports.IsEqual(Peek(state2), name);\n return result;\n }\n function CallDispatch(context2, state2, target, parameters, expression, arguments_) {\n InstantiationIncrement();\n try {\n const argumentsContext = ResolveArgumentsContext(context2, state2, parameters, arguments_);\n const returnType = InstantiateType(argumentsContext, State([...state2[\"callstack\"], target[\"$ref\"]], state2[\"visited\"]), expression);\n return InstantiateType(argumentsContext, State([], []), returnType);\n } finally {\n InstantiationDecrement();\n }\n }\n function CallDistributed(context2, state2, target, parameters, expression, distributedArguments) {\n return distributedArguments.reduce((result, arguments_) => {\n const returnType = CallDispatch(context2, state2, target, parameters, expression, arguments_);\n return [...result, returnType];\n }, []);\n }\n function CallImmediate(context2, state2, target, parameters, expression, arguments_) {\n const distributedArguments = DistributeArguments(parameters, arguments_, expression);\n const returnTypes = CallDistributed(context2, state2, target, parameters, expression, distributedArguments);\n const result = guard_exports.IsEqual(returnTypes.length, 1) ? returnTypes[0] : EvaluateUnion(returnTypes);\n return result;\n }\n function CallInstantiate(context2, state2, target, arguments_) {\n const instantiatedArguments = InstantiateTypes(context2, state2, arguments_);\n const resolved = ResolveTarget(context2, target, arguments_);\n const name = resolved[0];\n const type = resolved[1];\n const result = IsGeneric(type) ? IsTailCall(state2, name) ? CallConstruct(Ref2(name), instantiatedArguments) : CallImmediate(context2, state2, Ref2(name), type.parameters, type.expression, instantiatedArguments) : CallConstruct(target, instantiatedArguments);\n return result;\n }\n\n // node_modules/typebox/build/type/types/call.mjs\n function CallConstruct(target, arguments_) {\n return memory_exports.Create({ [\"~kind\"]: \"Call\" }, { type: \"call\", target, arguments: arguments_ }, {});\n }\n function Call2(target, arguments_) {\n return CallInstantiate({}, State([], []), target, arguments_);\n }\n function IsCall(value) {\n return IsKind(value, \"Call\");\n }\n\n // node_modules/typebox/build/type/engine/immutable/instantiate_remove.mjs\n function RemoveImmutableOperation(type) {\n return memory_exports.Discard(type, [\"~immutable\"]);\n }\n function RemoveImmutableAction(type, options) {\n const result = memory_exports.Update(RemoveImmutableOperation(type), {}, options);\n return result;\n }\n function RemoveImmutableInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return RemoveImmutableAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/engine/intrinsics/mapping.mjs\n function ApplyMapping(mapping, value) {\n return mapping(value);\n }\n\n // node_modules/typebox/build/type/engine/intrinsics/from_literal.mjs\n function FromLiteral3(mapping, value) {\n return guard_exports.IsString(value) ? Literal(ApplyMapping(mapping, value)) : Literal(value);\n }\n\n // node_modules/typebox/build/type/engine/intrinsics/from_template_literal.mjs\n function FromTemplateLiteral(mapping, pattern) {\n const evaluated = EvaluateTemplateLiteral(pattern);\n const result = FromType7(mapping, evaluated);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/intrinsics/from_union.mjs\n function FromUnion2(mapping, types) {\n const result = types.map((type) => FromType7(mapping, type));\n return Union(result);\n }\n\n // node_modules/typebox/build/type/engine/intrinsics/from_type.mjs\n function FromType7(mapping, type) {\n return IsLiteral(type) ? FromLiteral3(mapping, type.const) : IsTemplateLiteral(type) ? FromTemplateLiteral(mapping, type.pattern) : IsUnion(type) ? FromUnion2(mapping, type.anyOf) : type;\n }\n\n // node_modules/typebox/build/type/action/capitalize.mjs\n function CapitalizeDeferred(type, options = {}) {\n return Deferred(\"Capitalize\", [type], options);\n }\n function Capitalize(type, options = {}) {\n return CapitalizeAction(type, options);\n }\n\n // node_modules/typebox/build/type/action/lowercase.mjs\n function LowercaseDeferred(type, options = {}) {\n return Deferred(\"Lowercase\", [type], options);\n }\n function Lowercase(type, options = {}) {\n return LowercaseAction(type, options);\n }\n\n // node_modules/typebox/build/type/action/uncapitalize.mjs\n function UncapitalizeDeferred(type, options = {}) {\n return Deferred(\"Uncapitalize\", [type], options);\n }\n function Uncapitalize(type, options = {}) {\n return UncapitalizeAction(type, options);\n }\n\n // node_modules/typebox/build/type/action/uppercase.mjs\n function UppercaseDeferred(type, options = {}) {\n return Deferred(\"Uppercase\", [type], options);\n }\n function Uppercase(type, options = {}) {\n return UppercaseAction(type, options);\n }\n\n // node_modules/typebox/build/type/engine/intrinsics/instantiate.mjs\n var CapitalizeMapping = (input) => input[0].toUpperCase() + input.slice(1);\n var LowercaseMapping = (input) => input.toLowerCase();\n var UncapitalizeMapping = (input) => input[0].toLowerCase() + input.slice(1);\n var UppercaseMapping = (input) => input.toUpperCase();\n function CapitalizeAction(type, options) {\n const result = CanInstantiate([type]) ? memory_exports.Update(FromType7(CapitalizeMapping, type), {}, options) : CapitalizeDeferred(type, options);\n return result;\n }\n function LowercaseAction(type, options) {\n const result = CanInstantiate([type]) ? memory_exports.Update(FromType7(LowercaseMapping, type), {}, options) : LowercaseDeferred(type, options);\n return result;\n }\n function UncapitalizeAction(type, options) {\n const result = CanInstantiate([type]) ? memory_exports.Update(FromType7(UncapitalizeMapping, type), {}, options) : UncapitalizeDeferred(type, options);\n return result;\n }\n function UppercaseAction(type, options) {\n const result = CanInstantiate([type]) ? memory_exports.Update(FromType7(UppercaseMapping, type), {}, options) : UppercaseDeferred(type, options);\n return result;\n }\n function CapitalizeInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return CapitalizeAction(instantiatedType, options);\n }\n function LowercaseInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return LowercaseAction(instantiatedType, options);\n }\n function UncapitalizeInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return UncapitalizeAction(instantiatedType, options);\n }\n function UppercaseInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return UppercaseAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/action/conditional.mjs\n function ConditionalDeferred(left, right, true_, false_, options = {}) {\n return Deferred(\"Conditional\", [left, right, true_, false_], options);\n }\n function Conditional(left, right, true_, false_, options = {}) {\n return ConditionalAction({}, State([], []), left, right, true_, false_, options);\n }\n\n // node_modules/typebox/build/type/engine/conditional/instantiate.mjs\n function ConditionalOperation(context2, state2, left, right, true_, false_) {\n const extendsResult = Extends(context2, left, right);\n return result_exports.IsExtendsUnion(extendsResult) ? Union([InstantiateType(extendsResult.inferred, state2, true_), InstantiateType(context2, state2, false_)]) : result_exports.IsExtendsTrue(extendsResult) ? InstantiateType(extendsResult.inferred, state2, true_) : InstantiateType(context2, state2, false_);\n }\n function ConditionalAction(context2, state2, left, right, true_, false_, options) {\n const result = CanInstantiate([left, right]) ? memory_exports.Update(ConditionalOperation(context2, state2, left, right, true_, false_), {}, options) : ConditionalDeferred(left, right, true_, false_, options);\n return result;\n }\n function ConditionalInstantiate(context2, state2, left, right, true_, false_, options) {\n const instantiatedLeft = InstantiateType(context2, state2, left);\n const instantiatedRight = InstantiateType(context2, state2, right);\n return ConditionalAction(context2, state2, instantiatedLeft, instantiatedRight, true_, false_, options);\n }\n\n // node_modules/typebox/build/type/action/constructor_parameters.mjs\n function ConstructorParametersDeferred(type, options = {}) {\n return Deferred(\"ConstructorParameters\", [type], options);\n }\n function ConstructorParameters(type, options = {}) {\n return ConstructorParametersAction(type, options);\n }\n\n // node_modules/typebox/build/type/engine/constructor_parameters/instantiate.mjs\n function ConstructorParametersOperation(type) {\n const parameters = IsConstructor3(type) ? type[\"parameters\"] : [];\n const instantiatedParameters = InstantiateElements({}, State([], []), parameters);\n const result = Tuple(instantiatedParameters);\n return result;\n }\n function ConstructorParametersAction(type, options) {\n const result = CanInstantiate([type]) ? memory_exports.Update(ConstructorParametersOperation(type), {}, options) : ConstructorParametersDeferred(type, options);\n return result;\n }\n function ConstructorParametersInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return ConstructorParametersAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/action/exclude.mjs\n function ExcludeDeferred(left, right, options = {}) {\n return Deferred(\"Exclude\", [left, right], options);\n }\n function Exclude(left, right, options = {}) {\n return ExcludeAction(left, right, options);\n }\n\n // node_modules/typebox/build/type/engine/exclude/instantiate.mjs\n function ExcludeAction(left, right, options) {\n const result = CanInstantiate([left, right]) ? memory_exports.Update(ExcludeOperation(left, right), {}, options) : ExcludeDeferred(left, right, options);\n return result;\n }\n function ExcludeInstantiate(context2, state2, left, right, options) {\n const instantiatedLeft = InstantiateType(context2, state2, left);\n const instantiatedRight = InstantiateType(context2, state2, right);\n return ExcludeAction(instantiatedLeft, instantiatedRight, options);\n }\n\n // node_modules/typebox/build/type/action/extract.mjs\n function ExtractDeferred(left, right, options = {}) {\n return Deferred(\"Extract\", [left, right], options);\n }\n function Extract(left, right, options = {}) {\n return ExtractAction(left, right, options);\n }\n\n // node_modules/typebox/build/type/engine/extract/operation.mjs\n function ExtractType(left, right) {\n const check = Extends({}, left, right);\n const result = result_exports.IsExtendsTrueLike(check) ? [left] : [];\n return result;\n }\n function ExtractUnion(left, right, result = []) {\n return guard_exports.ShiftLeft(left, (head, tail) => ExtractUnion(tail, right, [...result, ...ExtractType(head, right)]), () => result);\n }\n function ExtractOperation(left, right) {\n const evaluated = EvaluateType(left);\n const canonical = IsUnion(evaluated) ? evaluated.anyOf : [evaluated];\n const remaining = ExtractUnion(canonical, right);\n const result = EvaluateUnion(remaining);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/extract/instantiate.mjs\n function ExtractAction(left, right, options) {\n const result = CanInstantiate([left, right]) ? memory_exports.Update(ExtractOperation(left, right), {}, options) : ExtractDeferred(left, right, options);\n return result;\n }\n function ExtractInstantiate(context2, state2, left, right, options) {\n const instantiatedLeft = InstantiateType(context2, state2, left);\n const instantiatedRight = InstantiateType(context2, state2, right);\n return ExtractAction(instantiatedLeft, instantiatedRight, options);\n }\n\n // node_modules/typebox/build/type/engine/helpers/keys_to_indexer.mjs\n function KeysToLiterals(keys) {\n return keys.reduce((result, left) => {\n return IsLiteralValue(left) ? [...result, Literal(left)] : result;\n }, []);\n }\n function KeysToIndexer(keys) {\n const literals = KeysToLiterals(keys);\n const result = Union(literals);\n return result;\n }\n\n // node_modules/typebox/build/type/action/indexed.mjs\n function IndexDeferred(type, indexer, options = {}) {\n return Deferred(\"Index\", [type, indexer], options);\n }\n function Index(type, indexer_or_keys, options = {}) {\n const indexer = guard_exports.IsArray(indexer_or_keys) ? KeysToIndexer(indexer_or_keys) : indexer_or_keys;\n return IndexAction(type, indexer, options);\n }\n\n // node_modules/typebox/build/type/engine/object/from_cyclic.mjs\n function FromCyclic(defs, ref) {\n const target = CyclicTarget(defs, ref);\n const result = FromType8(target);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/object/from_dependent.mjs\n function FromDependent(if_, then_, else_) {\n const evaluated = EvaluateDependent(if_, then_, else_);\n const result = FromType8(evaluated);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/object/from_intersect.mjs\n function CollapseIntersectProperties(left, right) {\n const leftKeys = guard_exports.Keys(left).filter((key) => !guard_exports.HasPropertyKey(right, key));\n const rightKeys = guard_exports.Keys(right).filter((key) => !guard_exports.HasPropertyKey(left, key));\n const sharedKeys = guard_exports.Keys(left).filter((key) => guard_exports.HasPropertyKey(right, key));\n const leftProperties = leftKeys.reduce((result, key) => ({ ...result, [key]: left[key] }), {});\n const rightProperties = rightKeys.reduce((result, key) => ({ ...result, [key]: right[key] }), {});\n const sharedProperties = sharedKeys.reduce((result, key) => ({ ...result, [key]: EvaluateIntersect([left[key], right[key]]) }), {});\n const unique = memory_exports.Assign(leftProperties, rightProperties);\n const shared = memory_exports.Assign(unique, sharedProperties);\n return shared;\n }\n function FromIntersect(types) {\n return types.reduce((result, left) => {\n return CollapseIntersectProperties(result, FromType8(left));\n }, {});\n }\n\n // node_modules/typebox/build/type/engine/object/from_object.mjs\n function FromObject5(properties) {\n return properties;\n }\n\n // node_modules/typebox/build/type/engine/object/from_tuple.mjs\n function FromTuple(types) {\n const object = TupleToObject(Tuple(types));\n const result = FromType8(object);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/object/from_union.mjs\n function CollapseUnionProperties(left, right) {\n const sharedKeys = guard_exports.Keys(left).filter((key) => key in right);\n const result = sharedKeys.reduce((result2, key) => {\n return { ...result2, [key]: EvaluateUnion([left[key], right[key]]) };\n }, {});\n return result;\n }\n function ReduceVariants(types, result) {\n return guard_exports.ShiftLeft(types, (left, right) => ReduceVariants(right, CollapseUnionProperties(result, FromType8(left))), () => result);\n }\n function FromUnion3(types) {\n return guard_exports.ShiftLeft(types, (left, right) => ReduceVariants(right, FromType8(left)), () => Unreachable());\n }\n\n // node_modules/typebox/build/type/engine/object/from_type.mjs\n function FromType8(type) {\n return IsCyclic(type) ? FromCyclic(type.$defs, type.$ref) : IsDependent(type) ? FromDependent(type.if, type.then, type.else) : IsIntersect(type) ? FromIntersect(type.allOf) : IsUnion(type) ? FromUnion3(type.anyOf) : IsTuple(type) ? FromTuple(type.items) : IsObject3(type) ? FromObject5(type.properties) : {};\n }\n\n // node_modules/typebox/build/type/engine/object/collapse.mjs\n function CollapseToObject(type) {\n const properties = FromType8(type);\n const result = _Object_(properties);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/helpers/keys.mjs\n var integerKeyPattern = new RegExp(\"^(?:0|[1-9][0-9]*)$\");\n function ConvertToIntegerKey(value) {\n const normal = `${value}`;\n return integerKeyPattern.test(normal) ? parseInt(normal) : value;\n }\n\n // node_modules/typebox/build/type/engine/indexed/from_array.mjs\n function NormalizeLiteral(value) {\n return Literal(ConvertToIntegerKey(value));\n }\n function NormalizeIndexerTypes(types) {\n return types.map((type) => NormalizeIndexer(type));\n }\n function NormalizeIndexer(type) {\n return IsIntersect(type) ? Intersect(NormalizeIndexerTypes(type.allOf)) : IsUnion(type) ? Union(NormalizeIndexerTypes(type.anyOf)) : IsLiteral(type) ? NormalizeLiteral(type.const) : type;\n }\n function FromArray4(type, indexer) {\n const normalizedIndexer = NormalizeIndexer(indexer);\n const check = Extends({}, normalizedIndexer, Number2());\n const result = (\n // indexer\n result_exports.IsExtendsTrueLike(check) ? type : IsLiteral(indexer) && guard_exports.IsEqual(indexer.const, \"length\") ? Number2() : Never()\n );\n return result;\n }\n\n // node_modules/typebox/build/type/engine/indexable/from_cyclic.mjs\n function FromCyclic2(defs, ref) {\n const target = CyclicTarget(defs, ref);\n const result = FromType9(target);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/indexable/from_dependent.mjs\n function FromDependent2(if_, then_, else_) {\n const evaluated = EvaluateDependent(if_, then_, else_);\n const result = FromType9(evaluated);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/indexable/from_enum.mjs\n function FromEnum(values) {\n const evaluated = EvaluateEnum(values);\n const result = FromType9(evaluated);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/indexable/from_intersect.mjs\n function FromIntersect2(types) {\n const evaluated = EvaluateIntersect(types);\n const result = FromType9(evaluated);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/indexable/from_literal.mjs\n function FromLiteral4(value) {\n const result = [`${value}`];\n return result;\n }\n\n // node_modules/typebox/build/type/engine/indexable/from_template_literal.mjs\n function FromTemplateLiteral2(pattern) {\n const evaluated = EvaluateTemplateLiteral(pattern);\n const result = FromType9(evaluated);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/indexable/from_union.mjs\n function FromUnion4(types) {\n return types.reduce((result, left) => {\n return [...result, ...FromType9(left)];\n }, []);\n }\n\n // node_modules/typebox/build/type/engine/indexable/from_type.mjs\n function FromType9(type) {\n return IsCyclic(type) ? FromCyclic2(type.$defs, type.$ref) : IsDependent(type) ? FromDependent2(type.if, type.then, type.else) : IsEnum2(type) ? FromEnum(type.enum) : IsIntersect(type) ? FromIntersect2(type.allOf) : IsLiteral(type) ? FromLiteral4(type.const) : IsTemplateLiteral(type) ? FromTemplateLiteral2(type.pattern) : IsUnion(type) ? FromUnion4(type.anyOf) : [];\n }\n\n // node_modules/typebox/build/type/engine/indexable/to_indexable_keys.mjs\n function ToIndexableKeys(type) {\n const result = FromType9(type);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/this/expand_this.mjs\n function FromTypes5(properties, types) {\n return types.map((type) => FromType10(properties, type));\n }\n function FromType10(properties, type) {\n return IsArray3(type) ? _Array_(FromType10(properties, type.items)) : IsConstructor3(type) ? Constructor(FromTypes5(properties, type.parameters), FromType10(properties, type.instanceType)) : IsFunction3(type) ? _Function_(FromTypes5(properties, type.parameters), FromType10(properties, type.returnType)) : IsTuple(type) ? Tuple(FromTypes5(properties, type.items)) : IsUnion(type) ? Union(FromTypes5(properties, type.anyOf)) : IsIntersect(type) ? Intersect(FromTypes5(properties, type.allOf)) : IsThis(type) ? _Object_(properties) : type;\n }\n function ExpandThis(properties, type) {\n const result = FromType10(properties, type);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/indexed/from_object.mjs\n function IndexProperty(properties, key) {\n const selectedType = key in properties ? properties[key] : Never();\n const result = ExpandThis(properties, selectedType);\n return result;\n }\n function IndexProperties(properties, keys) {\n return keys.reduce((result, left) => {\n return [...result, IndexProperty(properties, left)];\n }, []);\n }\n function FromIndexer(properties, indexer) {\n const keys = ToIndexableKeys(indexer);\n const variants = IndexProperties(properties, keys);\n const result = EvaluateUnion(variants);\n return result;\n }\n var NumericKeyPattern = new RegExp(IntegerKey);\n function NumericKeys(keys) {\n const result = keys.filter((key) => NumericKeyPattern.test(key));\n return result;\n }\n function FromIndexerNumber(properties) {\n const keys = PropertyKeys(properties);\n const numericKeys = NumericKeys(keys);\n const variants = IndexProperties(properties, numericKeys);\n const result = EvaluateUnion(variants);\n return result;\n }\n function FromObject6(properties, indexer) {\n const result = IsNumber4(indexer) ? FromIndexerNumber(properties) : FromIndexer(properties, indexer);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/indexed/array_indexer.mjs\n function ConvertLiteral(value) {\n return Literal(ConvertToIntegerKey(value));\n }\n function ArrayIndexerTypes(types) {\n return types.map((type) => FormatArrayIndexer(type));\n }\n function FormatArrayIndexer(type) {\n return IsIntersect(type) ? Intersect(ArrayIndexerTypes(type.allOf)) : IsUnion(type) ? Union(ArrayIndexerTypes(type.anyOf)) : IsLiteral(type) ? ConvertLiteral(type.const) : type;\n }\n\n // node_modules/typebox/build/type/engine/indexed/from_tuple.mjs\n function IndexElementsWithIndexer(types, indexer) {\n return types.reduceRight((result, right, index3) => {\n const check = Extends({}, Literal(index3), indexer);\n return result_exports.IsExtendsTrueLike(check) ? [right, ...result] : result;\n }, []);\n }\n function FromTupleWithIndexer(types, indexer) {\n const formattedArrayIndexer = FormatArrayIndexer(indexer);\n const elements = IndexElementsWithIndexer(types, formattedArrayIndexer);\n return EvaluateUnionFast(elements);\n }\n function FromTupleWithoutIndexer(types) {\n return EvaluateUnionFast(types);\n }\n function FromTuple2(types, indexer) {\n return (\n // length (intrinsic)\n IsLiteral(indexer) && guard_exports.IsEqual(indexer.const, \"length\") ? Literal(types.length) : IsNumber4(indexer) || IsInteger3(indexer) ? FromTupleWithoutIndexer(types) : FromTupleWithIndexer(types, indexer)\n );\n }\n\n // node_modules/typebox/build/type/engine/indexed/from_type.mjs\n function FromType11(type, indexer) {\n return IsArray3(type) ? FromArray4(type.items, indexer) : IsObject3(type) ? FromObject6(type.properties, indexer) : IsTuple(type) ? FromTuple2(type.items, indexer) : Never();\n }\n\n // node_modules/typebox/build/type/engine/indexed/instantiate.mjs\n function NormalizeType(type) {\n const result = IsCyclic(type) || IsDependent(type) || IsIntersect(type) || IsUnion(type) ? CollapseToObject(type) : type;\n return result;\n }\n function IndexAction(type, indexer, options) {\n const result = CanInstantiate([type, indexer]) ? memory_exports.Update(FromType11(NormalizeType(type), indexer), {}, options) : IndexDeferred(type, indexer, options);\n return result;\n }\n function IndexInstantiate(context2, state2, type, indexer, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n const instantiatedIndexer = InstantiateType(context2, state2, indexer);\n return IndexAction(instantiatedType, instantiatedIndexer, options);\n }\n\n // node_modules/typebox/build/type/action/instance_type.mjs\n function InstanceTypeDeferred(type, options = {}) {\n return Deferred(\"InstanceType\", [type], options);\n }\n function InstanceType(type, options = {}) {\n return InstanceTypeAction(type, options);\n }\n\n // node_modules/typebox/build/type/engine/instance_type/instantiate.mjs\n function InstanceTypeOperation(type) {\n return IsConstructor3(type) ? type[\"instanceType\"] : Never();\n }\n function InstanceTypeAction(type, options) {\n const result = CanInstantiate([type]) ? memory_exports.Update(InstanceTypeOperation(type), {}, options) : InstanceTypeDeferred(type, options);\n return result;\n }\n function InstanceTypeInstantiate(context2, state2, type, options = {}) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return InstanceTypeAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/action/keyof.mjs\n function KeyOfDeferred(type, options = {}) {\n return Deferred(\"KeyOf\", [type], options);\n }\n function KeyOf2(type, options = {}) {\n return KeyOfAction(type, options);\n }\n\n // node_modules/typebox/build/type/engine/keyof/from_any.mjs\n function FromAny() {\n return Union([Number2(), String2(), Symbol2()]);\n }\n\n // node_modules/typebox/build/type/engine/keyof/from_array.mjs\n function FromArray5(_type) {\n return Number2();\n }\n\n // node_modules/typebox/build/type/engine/keyof/from_object.mjs\n function FromPropertyKeys(keys) {\n const result = keys.reduce((result2, left) => {\n return IsLiteralValue(left) ? [...result2, Literal(ConvertToIntegerKey(left))] : Unreachable();\n }, []);\n return result;\n }\n function FromObject7(properties) {\n const propertyKeys = guard_exports.Keys(properties);\n const variants = FromPropertyKeys(propertyKeys);\n const result = EvaluateUnionFast(variants);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/keyof/from_record.mjs\n function FromRecord2(type) {\n return RecordKey(type);\n }\n\n // node_modules/typebox/build/type/engine/keyof/from_tuple.mjs\n function FromTuple3(types) {\n const result = types.map((_, index3) => Literal(index3));\n return EvaluateUnionFast(result);\n }\n\n // node_modules/typebox/build/type/engine/keyof/from_type.mjs\n function FromType12(type) {\n return IsAny(type) ? FromAny() : IsArray3(type) ? FromArray5(type.items) : IsObject3(type) ? FromObject7(type.properties) : IsRecord(type) ? FromRecord2(type) : IsTuple(type) ? FromTuple3(type.items) : Never();\n }\n\n // node_modules/typebox/build/type/engine/keyof/instantiate.mjs\n function NormalizeType2(type) {\n const result = IsCyclic(type) || IsDependent(type) || IsIntersect(type) || IsUnion(type) ? CollapseToObject(type) : type;\n return result;\n }\n function KeyOfAction(type, options) {\n return CanInstantiate([type]) ? memory_exports.Update(FromType12(NormalizeType2(type)), {}, options) : KeyOfDeferred(type, options);\n }\n function KeyOfInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return KeyOfAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/action/mapped.mjs\n function MappedDeferred(identifier, type, as, property, options = {}) {\n return Deferred(\"Mapped\", [identifier, type, as, property], options);\n }\n function Mapped(identifier, type, as, property, options = {}) {\n return MappedAction({}, State([], []), identifier, type, as, property, options);\n }\n\n // node_modules/typebox/build/type/engine/mapped/mapped_variants.mjs\n function FromTemplateLiteral3(pattern) {\n const evaluated = EvaluateTemplateLiteral(pattern);\n const result = FromType13(evaluated);\n return result;\n }\n function FromUnion5(types) {\n return types.reduce((result, left) => {\n return [...result, ...FromType13(left)];\n }, []);\n }\n function FromEnum2(values) {\n const evaluated = EvaluateEnum(values);\n const result = FromType13(evaluated);\n return result;\n }\n function FromLiteral5(value) {\n const result = guard_exports.IsNumber(value) ? [Literal(`${value}`)] : [Literal(value)];\n return result;\n }\n function FromType13(type) {\n const result = IsEnum2(type) ? FromEnum2(type.enum) : IsLiteral(type) ? FromLiteral5(type.const) : IsTemplateLiteral(type) ? FromTemplateLiteral3(type.pattern) : IsUnion(type) ? FromUnion5(type.anyOf) : [type];\n return result;\n }\n function MappedVariants(type) {\n const result = FromType13(type);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/mapped/mapped_operation.mjs\n function CanonicalAs(instantiatedAs) {\n const result = IsTemplateLiteral(instantiatedAs) ? EvaluateTemplateLiteral(instantiatedAs.pattern) : instantiatedAs;\n return result;\n }\n function MappedVariant(context2, state2, identifier, variant, as, property) {\n const variantContext = memory_exports.Assign(context2, { [identifier[\"name\"]]: variant });\n const instantiatedAs = InstantiateType(variantContext, state2, as);\n const canonicalAs = CanonicalAs(instantiatedAs);\n const instantiatedProperty = InstantiateType(variantContext, state2, property);\n return IsLiteralNumber(canonicalAs) || IsLiteralString(canonicalAs) ? { [canonicalAs.const]: instantiatedProperty } : {};\n }\n function MappedProperties(context2, state2, identifier, variants, as, property) {\n return variants.reduce((result, left) => {\n return [...result, MappedVariant(context2, state2, identifier, left, as, property)];\n }, []);\n }\n function MappedObjects(properties) {\n return properties.reduce((result, left) => {\n return [...result, _Object_(left)];\n }, []);\n }\n function MappedOperation(context2, state2, identifier, type, as, property) {\n const variants = MappedVariants(type);\n const mappedProperties = MappedProperties(context2, state2, identifier, variants, as, property);\n const mappedObjects = MappedObjects(mappedProperties);\n const result = EvaluateIntersect(mappedObjects);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/mapped/instantiate.mjs\n function MappedAction(context2, state2, identifier, type, as, property, options) {\n const result = CanInstantiate([type]) ? memory_exports.Update(MappedOperation(context2, state2, identifier, type, as, property), {}, options) : MappedDeferred(identifier, type, as, property, options);\n return result;\n }\n function MappedInstantiate(context2, state2, identifier, type, as, property, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return MappedAction(context2, state2, identifier, instantiatedType, as, property, options);\n }\n\n // node_modules/typebox/build/type/engine/module/instantiate.mjs\n function InstantiateCyclics(context2, declarations, cyclicKeys) {\n const declarationContext = memory_exports.Assign(context2, declarations);\n const declarationKeys = guard_exports.Keys(declarations).filter((key) => cyclicKeys.includes(key));\n return declarationKeys.reduce((result, key) => {\n return { ...result, [key]: InstantiateCyclic(declarationContext, key, declarations[key]) };\n }, {});\n }\n function InstantiateNonCyclics(context2, declarations, cyclicKeys) {\n const declarationContext = memory_exports.Assign(context2, declarations);\n const declarationKeys = guard_exports.Keys(declarations).filter((key) => !cyclicKeys.includes(key));\n return declarationKeys.reduce((result, key) => {\n return { ...result, [key]: InstantiateType(declarationContext, State([], []), declarations[key]) };\n }, {});\n }\n function InstantiateModule(context2, declarations, options) {\n const cyclicCandidates = CyclicCandidates(declarations);\n const instantiatedCyclics = InstantiateCyclics(context2, declarations, cyclicCandidates);\n const instantiatedNonCyclics = InstantiateNonCyclics(context2, declarations, cyclicCandidates);\n const instantiatedModule = { ...instantiatedCyclics, ...instantiatedNonCyclics };\n return memory_exports.Update(instantiatedModule, {}, options);\n }\n function ModuleInstantiate(context2, _state, declarations, options) {\n const instantiatedModule = InstantiateModule(context2, declarations, options);\n return instantiatedModule;\n }\n\n // node_modules/typebox/build/type/action/non_nullable.mjs\n function NonNullableDeferred(type, options = {}) {\n return Deferred(\"NonNullable\", [type], options);\n }\n function NonNullable(type, options = {}) {\n return NonNullableAction(type, options);\n }\n\n // node_modules/typebox/build/type/engine/non_nullable/instantiate.mjs\n function NonNullableOperation(type) {\n const excluded = Union([Null(), Undefined()]);\n return ExcludeAction(type, excluded, {});\n }\n function NonNullableAction(type, options) {\n const result = CanInstantiate([type]) ? memory_exports.Update(NonNullableOperation(type), {}, options) : NonNullableDeferred(type, options);\n return result;\n }\n function NonNullableInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return NonNullableAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/action/omit.mjs\n function OmitDeferred(type, indexer, options = {}) {\n return Deferred(\"Omit\", [type, indexer], options);\n }\n function Omit(type, indexer_or_keys, options = {}) {\n const indexer = guard_exports.IsArray(indexer_or_keys) ? KeysToIndexer(indexer_or_keys) : indexer_or_keys;\n return OmitAction(type, indexer, options);\n }\n\n // node_modules/typebox/build/type/engine/indexable/to_indexable.mjs\n function ToIndexable(type) {\n const collapsed = CollapseToObject(type);\n const result = IsObject3(collapsed) ? collapsed.properties : Unreachable();\n return result;\n }\n\n // node_modules/typebox/build/type/engine/omit/from_type.mjs\n function FromKeys(properties, keys) {\n const result = guard_exports.Keys(properties).reduce((result2, key) => {\n return keys.includes(key) ? result2 : { ...result2, [key]: properties[key] };\n }, {});\n return result;\n }\n function FromType14(type, indexer) {\n const indexable = ToIndexable(type);\n const indexableKeys = ToIndexableKeys(indexer);\n const omitted = FromKeys(indexable, indexableKeys);\n const result = _Object_(omitted);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/omit/instantiate.mjs\n function OmitAction(type, indexer, options) {\n const result = CanInstantiate([type, indexer]) ? memory_exports.Update(FromType14(type, indexer), {}, options) : OmitDeferred(type, indexer, options);\n return result;\n }\n function OmitInstantiate(context2, state2, type, indexer, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n const instantiatedIndexer = InstantiateType(context2, state2, indexer);\n return OmitAction(instantiatedType, instantiatedIndexer, options);\n }\n\n // node_modules/typebox/build/type/action/parameters.mjs\n function ParametersDeferred(type, options = {}) {\n return Deferred(\"Parameters\", [type], options);\n }\n function Parameters(type, options = {}) {\n return ParametersAction(type, options);\n }\n\n // node_modules/typebox/build/type/engine/parameters/instantiate.mjs\n function ParametersOperation(type) {\n const parameters = IsFunction3(type) ? type[\"parameters\"] : [];\n const instantiatedParameters = InstantiateElements({}, State([], []), parameters);\n const result = Tuple(instantiatedParameters);\n return result;\n }\n function ParametersAction(type, options) {\n const result = CanInstantiate([type]) ? memory_exports.Update(ParametersOperation(type), {}, options) : ParametersDeferred(type, options);\n return result;\n }\n function ParametersInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return ParametersAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/action/partial.mjs\n function PartialDeferred(type, options = {}) {\n return Deferred(\"Partial\", [type], options);\n }\n function Partial(type, options = {}) {\n return PartialAction(type, options);\n }\n\n // node_modules/typebox/build/type/engine/partial/from_cyclic.mjs\n function FromCyclic3(defs, ref) {\n const target = CyclicTarget(defs, ref);\n const partial = FromType15(target);\n const result = Cyclic(memory_exports.Assign(defs, { [ref]: partial }), ref);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/partial/from_dependent.mjs\n function FromDependent3(if_, then_, else_) {\n const evaluated = EvaluateDependent(if_, then_, else_);\n const result = FromType15(evaluated);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/partial/from_intersect.mjs\n function FromIntersect3(types) {\n const evaluated = EvaluateIntersect(types);\n const result = FromType15(evaluated);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/partial/from_union.mjs\n function FromUnion6(types) {\n const result = types.map((type) => FromType15(type));\n return Union(result);\n }\n\n // node_modules/typebox/build/type/engine/partial/from_object.mjs\n function FromObject8(properties) {\n const mapped = guard_exports.Keys(properties).reduce((result2, left) => {\n return { ...result2, [left]: AddOptional(properties[left]) };\n }, {});\n const result = _Object_(mapped);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/partial/from_type.mjs\n function FromType15(type) {\n return IsCyclic(type) ? FromCyclic3(type.$defs, type.$ref) : IsDependent(type) ? FromDependent3(type.if, type.then, type.else) : IsIntersect(type) ? FromIntersect3(type.allOf) : IsUnion(type) ? FromUnion6(type.anyOf) : IsObject3(type) ? FromObject8(type.properties) : _Object_({});\n }\n\n // node_modules/typebox/build/type/engine/partial/instantiate.mjs\n function PartialAction(type, options) {\n const result = CanInstantiate([type]) ? memory_exports.Update(FromType15(type), {}, options) : PartialDeferred(type, options);\n return result;\n }\n function PartialInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return PartialAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/action/pick.mjs\n function PickDeferred(type, indexer, options = {}) {\n return Deferred(\"Pick\", [type, indexer], options);\n }\n function Pick(type, indexer_or_keys, options = {}) {\n const indexer = guard_exports.IsArray(indexer_or_keys) ? KeysToIndexer(indexer_or_keys) : indexer_or_keys;\n return PickAction(type, indexer, options);\n }\n\n // node_modules/typebox/build/type/engine/pick/from_type.mjs\n function FromKeys2(properties, keys) {\n const result = guard_exports.Keys(properties).reduce((result2, key) => {\n return keys.includes(key) ? memory_exports.Assign(result2, { [key]: properties[key] }) : result2;\n }, {});\n return result;\n }\n function FromType16(type, indexer) {\n const indexable = ToIndexable(type);\n const keys = ToIndexableKeys(indexer);\n const applied = FromKeys2(indexable, keys);\n const result = _Object_(applied);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/pick/instantiate.mjs\n function PickAction(type, indexer, options) {\n const result = CanInstantiate([type, indexer]) ? memory_exports.Update(FromType16(type, indexer), {}, options) : PickDeferred(type, indexer, options);\n return result;\n }\n function PickInstantiate(context2, state2, type, indexer, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n const instantiatedIndexer = InstantiateType(context2, state2, indexer);\n return PickAction(instantiatedType, instantiatedIndexer, options);\n }\n\n // node_modules/typebox/build/type/action/readonly_object.mjs\n function ReadonlyObjectDeferred(type, options = {}) {\n return Deferred(\"ReadonlyObject\", [type], options);\n }\n function ReadonlyObject(type, options = {}) {\n return ReadonlyObjectAction(type, options);\n }\n var ReadonlyType = ReadonlyObject;\n\n // node_modules/typebox/build/type/engine/readonly_object/from_array.mjs\n function FromArray6(type) {\n const result = AddImmutable(_Array_(type));\n return result;\n }\n\n // node_modules/typebox/build/type/engine/readonly_object/from_cyclic.mjs\n function FromCyclic4(defs, ref) {\n const target = CyclicTarget(defs, ref);\n const partial = FromType17(target);\n const result = Cyclic(memory_exports.Assign(defs, { [ref]: partial }), ref);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/readonly_object/from_dependent.mjs\n function FromDependent4(if_, then_, else_) {\n const evaluated = EvaluateDependent(if_, then_, else_);\n const result = FromType17(evaluated);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/readonly_object/from_intersect.mjs\n function FromIntersect4(types) {\n const evaluated = EvaluateIntersect(types);\n const result = FromType17(evaluated);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/readonly_object/from_object.mjs\n function FromObject9(properties) {\n const mapped = guard_exports.Keys(properties).reduce((result2, left) => {\n return { ...result2, [left]: AddReadonly(properties[left]) };\n }, {});\n const result = _Object_(mapped);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/readonly_object/from_tuple.mjs\n function FromTuple4(types) {\n const result = AddImmutable(Tuple(types));\n return result;\n }\n\n // node_modules/typebox/build/type/engine/readonly_object/from_union.mjs\n function FromUnion7(types) {\n const result = types.map((type) => FromType17(type));\n return Union(result);\n }\n\n // node_modules/typebox/build/type/engine/readonly_object/from_type.mjs\n function FromType17(type) {\n return IsArray3(type) ? FromArray6(type.items) : IsCyclic(type) ? FromCyclic4(type.$defs, type.$ref) : IsDependent(type) ? FromDependent4(type.if, type.then, type.else) : IsIntersect(type) ? FromIntersect4(type.allOf) : IsObject3(type) ? FromObject9(type.properties) : IsTuple(type) ? FromTuple4(type.items) : IsUnion(type) ? FromUnion7(type.anyOf) : type;\n }\n\n // node_modules/typebox/build/type/engine/readonly_object/instantiate.mjs\n function ReadonlyObjectAction(type, options) {\n const result = CanInstantiate([type]) ? memory_exports.Update(FromType17(type), {}, options) : ReadonlyObjectDeferred(type);\n return result;\n }\n function ReadonlyObjectInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return ReadonlyObjectAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/engine/ref/instantiate.mjs\n function RefInstantiate(context2, state2, type, ref) {\n return state2.visited.includes(ref) ? type : ref in context2 ? InstantiateType(context2, State(state2[\"callstack\"], [...state2[\"visited\"], ref]), context2[ref]) : type;\n }\n\n // node_modules/typebox/build/type/engine/required/from_cyclic.mjs\n function FromCyclic5(defs, ref) {\n const target = CyclicTarget(defs, ref);\n const partial = FromType18(target);\n const result = Cyclic(memory_exports.Assign(defs, { [ref]: partial }), ref);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/required/from_dependent.mjs\n function FromDependent5(if_, then_, else_) {\n const evaluated = EvaluateDependent(if_, then_, else_);\n const result = FromType18(evaluated);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/required/from_intersect.mjs\n function FromIntersect5(types) {\n const evaluated = EvaluateIntersect(types);\n const result = FromType18(evaluated);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/required/from_union.mjs\n function FromUnion8(types) {\n const result = types.map((type) => FromType18(type));\n return Union(result);\n }\n\n // node_modules/typebox/build/type/engine/required/from_object.mjs\n function FromObject10(properties) {\n const mapped = guard_exports.Keys(properties).reduce((result2, left) => {\n return { ...result2, [left]: RemoveOptional(properties[left]) };\n }, {});\n const result = _Object_(mapped);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/required/from_type.mjs\n function FromType18(type) {\n return IsCyclic(type) ? FromCyclic5(type.$defs, type.$ref) : IsDependent(type) ? FromDependent5(type.if, type.then, type.else) : IsIntersect(type) ? FromIntersect5(type.allOf) : IsUnion(type) ? FromUnion8(type.anyOf) : IsObject3(type) ? FromObject10(type.properties) : _Object_({});\n }\n\n // node_modules/typebox/build/type/action/required.mjs\n function RequiredDeferred(type, options = {}) {\n return Deferred(\"Required\", [type], options);\n }\n function Required(type, options = {}) {\n return RequiredAction(type, options);\n }\n\n // node_modules/typebox/build/type/engine/required/instantiate.mjs\n function RequiredAction(type, options) {\n const result = CanInstantiate([type]) ? memory_exports.Update(FromType18(type), {}, options) : RequiredDeferred(type, options);\n return result;\n }\n function RequiredInstantiate(context2, state2, type, options) {\n const instaniatedType = InstantiateType(context2, state2, type);\n return RequiredAction(instaniatedType, options);\n }\n\n // node_modules/typebox/build/type/action/return_type.mjs\n function ReturnTypeDeferred(type, options = {}) {\n return Deferred(\"ReturnType\", [type], options);\n }\n function ReturnType(type, options = {}) {\n return ReturnTypeAction(type, options);\n }\n\n // node_modules/typebox/build/type/engine/return_type/instantiate.mjs\n function ReturnTypeOperation(type) {\n return IsFunction3(type) ? type[\"returnType\"] : Never();\n }\n function ReturnTypeAction(type, options) {\n const result = CanInstantiate([type]) ? memory_exports.Update(ReturnTypeOperation(type), {}, options) : ReturnTypeDeferred(type, options);\n return result;\n }\n function ReturnTypeInstantiate(context2, state2, type, options = {}) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return ReturnTypeAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/action/with.mjs\n function WithDeferred(type, options) {\n return Deferred(\"With\", [type, options], {});\n }\n function With2(type, options) {\n return WithAction(type, options);\n }\n\n // node_modules/typebox/build/type/engine/with/instantiate.mjs\n function WithAction(type, options) {\n const result = CanInstantiate([type]) ? memory_exports.Update(type, {}, options) : WithDeferred(type, options);\n return result;\n }\n function WithInstantiate(context2, state2, type, options) {\n const instaniatedType = InstantiateType(context2, state2, type);\n return WithAction(instaniatedType, options);\n }\n\n // node_modules/typebox/build/type/engine/rest/spread.mjs\n function SpreadElement(type) {\n const result = IsRest(type) ? IsTuple(type.items) ? RestSpread(type.items.items) : IsInfer(type.items) ? [type] : IsRef2(type.items) ? [type] : [Never()] : [type];\n return result;\n }\n function RestSpread(types) {\n const result = types.reduce((result2, left) => {\n return [...result2, ...SpreadElement(left)];\n }, []);\n return result;\n }\n\n // node_modules/typebox/build/type/engine/instantiate.mjs\n function State(callstack, visited2) {\n return { callstack, visited: visited2 };\n }\n function CanInstantiate(types) {\n return guard_exports.ShiftLeft(types, (left, right) => IsRef2(left) ? false : CanInstantiate(right), () => true);\n }\n function InstantiateProperties(context2, state2, properties) {\n return guard_exports.Keys(properties).reduce((result, key) => {\n return { ...result, [key]: InstantiateType(context2, state2, properties[key]) };\n }, {});\n }\n function InstantiateElements(context2, state2, types) {\n const elements = InstantiateTypes(context2, state2, types);\n const result = RestSpread(elements);\n return result;\n }\n function InstantiateTypes(context2, state2, types) {\n return types.map((type) => InstantiateType(context2, state2, type));\n }\n function WithModifiers(type, instantiatedType) {\n const withOptional = IsOptional(type) ? AddOptionalAction(instantiatedType, {}) : instantiatedType;\n const withReadonly = IsReadonly(type) ? AddReadonlyAction(withOptional, {}) : withOptional;\n const withImmutable = IsImmutable(type) ? AddImmutableAction(withReadonly, {}) : withReadonly;\n return withImmutable;\n }\n function InstantiateDeferred(context2, state2, action, parameters, options) {\n return (\n // Modifiers\n guard_exports.IsEqual(action, \"AddImmutable\") ? AddImmutableInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"RemoveImmutable\") ? RemoveImmutableInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"AddReadonly\") ? AddReadonlyInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"RemoveReadonly\") ? RemoveReadonlyInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"AddOptional\") ? AddOptionalInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"RemoveOptional\") ? RemoveOptionalInstantiate(context2, state2, parameters[0], options) : (\n // Actions\n guard_exports.IsEqual(action, \"Capitalize\") ? CapitalizeInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"Conditional\") ? ConditionalInstantiate(context2, state2, parameters[0], parameters[1], parameters[2], parameters[3], options) : guard_exports.IsEqual(action, \"ConstructorParameters\") ? ConstructorParametersInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"Evaluate\") ? EvaluateInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"Exclude\") ? ExcludeInstantiate(context2, state2, parameters[0], parameters[1], options) : guard_exports.IsEqual(action, \"Extract\") ? ExtractInstantiate(context2, state2, parameters[0], parameters[1], options) : guard_exports.IsEqual(action, \"Index\") ? IndexInstantiate(context2, state2, parameters[0], parameters[1], options) : guard_exports.IsEqual(action, \"InstanceType\") ? InstanceTypeInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"Interface\") ? InterfaceInstantiate(context2, state2, parameters[0], parameters[1], options) : guard_exports.IsEqual(action, \"KeyOf\") ? KeyOfInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"Lowercase\") ? LowercaseInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"Mapped\") ? MappedInstantiate(context2, state2, parameters[0], parameters[1], parameters[2], parameters[3], options) : guard_exports.IsEqual(action, \"Module\") ? ModuleInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"NonNullable\") ? NonNullableInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"Pick\") ? PickInstantiate(context2, state2, parameters[0], parameters[1], options) : guard_exports.IsEqual(action, \"Parameters\") ? ParametersInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"Partial\") ? PartialInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"Omit\") ? OmitInstantiate(context2, state2, parameters[0], parameters[1], options) : guard_exports.IsEqual(action, \"ReadonlyObject\") ? ReadonlyObjectInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"Record\") ? RecordInstantiate(context2, state2, parameters[0], parameters[1], options) : guard_exports.IsEqual(action, \"Required\") ? RequiredInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"ReturnType\") ? ReturnTypeInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"TemplateLiteral\") ? TemplateLiteralInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"Uncapitalize\") ? UncapitalizeInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"Uppercase\") ? UppercaseInstantiate(context2, state2, parameters[0], options) : guard_exports.IsEqual(action, \"With\") ? WithInstantiate(context2, state2, parameters[0], parameters[1]) : Deferred(action, parameters, options)\n )\n );\n }\n function InstantiateImmediate(context2, state2, type) {\n const instantiatedType = IsRef2(type) ? RefInstantiate(context2, state2, type, type.$ref) : IsArray3(type) ? _Array_(InstantiateType(context2, state2, type.items), ArrayOptions(type)) : IsCall(type) ? CallInstantiate(context2, state2, type.target, type.arguments) : IsConstructor3(type) ? Constructor(InstantiateTypes(context2, state2, type.parameters), InstantiateType(context2, state2, type.instanceType), ConstructorOptions(type)) : IsFunction3(type) ? _Function_(InstantiateTypes(context2, state2, type.parameters), InstantiateType(context2, state2, type.returnType), FunctionOptions(type)) : IsDependent(type) ? Dependent(InstantiateType(context2, state2, type.if), InstantiateType(context2, state2, type.then), InstantiateType(context2, state2, type.else), DependentOptions(type)) : IsIntersect(type) ? Intersect(InstantiateTypes(context2, state2, type.allOf), IntersectOptions(type)) : IsObject3(type) ? _Object_(InstantiateProperties(context2, state2, type.properties), ObjectOptions(type)) : IsRecord(type) ? RecordFromPattern(RecordPattern(type), InstantiateType(context2, state2, RecordValue(type))) : IsRest(type) ? Rest(InstantiateType(context2, state2, type.items)) : IsTuple(type) ? Tuple(InstantiateElements(context2, state2, type.items), TupleOptions(type)) : IsUnion(type) ? Union(InstantiateTypes(context2, state2, type.anyOf), UnionOptions(type)) : type;\n const withModifiers = WithModifiers(type, instantiatedType);\n return withModifiers;\n }\n function InstantiateType(context2, state2, type) {\n const result = IsDeferred(type) ? InstantiateDeferred(context2, state2, type.action, type.parameters, type.options) : InstantiateImmediate(context2, state2, type);\n return result;\n }\n function Instantiate(context2, type) {\n return InstantiateType(context2, State([], []), type);\n }\n\n // node_modules/typebox/build/type/engine/immutable/instantiate_add.mjs\n function AddImmutableOperation(type) {\n return memory_exports.Update(type, { \"~immutable\": true }, {});\n }\n function AddImmutableAction(type, options) {\n const result = memory_exports.Update(AddImmutableOperation(type), {}, options);\n return result;\n }\n function AddImmutableInstantiate(context2, state2, type, options) {\n const instantiatedType = InstantiateType(context2, state2, type);\n return AddImmutableAction(instantiatedType, options);\n }\n\n // node_modules/typebox/build/type/action/_add_immutable.mjs\n function AddImmutableDeferred(type, options = {}) {\n return Deferred(\"AddImmutable\", [type], options);\n }\n function AddImmutable(type, options = {}) {\n return AddImmutableAction(type, options);\n }\n\n // node_modules/typebox/build/type/action/evaluate.mjs\n function EvaluateDeferred(type, options = {}) {\n return Deferred(\"Evaluate\", [type], options);\n }\n function Evaluate2(type, options = {}) {\n return EvaluateAction(type, options);\n }\n\n // node_modules/typebox/build/type/action/module.mjs\n function ModuleDeferred(declarations, options = {}) {\n return Deferred(\"Module\", [declarations], options);\n }\n function Module2(declarations, options = {}) {\n return ModuleInstantiate({}, State([], []), declarations, options);\n }\n\n // node_modules/typebox/build/type/engine/priority/priority.mjs\n function Comparer(left, right) {\n const compareResult = Compare(left, right);\n return guard_exports.IsEqual(compareResult, CompareResultRightInside) ? 1 : guard_exports.IsEqual(compareResult, CompareResultDisjoint) ? 1 : 0;\n }\n function Insert(type, types, result = []) {\n return guard_exports.ShiftLeft(types, (left, right) => guard_exports.IsEqual(Comparer(type, left), 1) ? Insert(type, right, [...result, left]) : [...result, type, ...types], () => [...result, type]);\n }\n function Sort(types, result = []) {\n return guard_exports.ShiftLeft(types, (left, right) => Sort(right, Insert(left, result)), () => result);\n }\n function Priority(types) {\n const result = Sort(types);\n return result;\n }\n\n // node_modules/typebox/build/type/script/script.mjs\n function Script2(...args) {\n const [context2, input, options] = arguments_exports.Match(args, {\n 2: (script, options2) => guard_exports.IsString(script) ? [{}, script, options2] : [script, options2, {}],\n 3: (context3, script, options2) => [context3, script, options2],\n 1: (script) => [{}, script, {}]\n });\n const result = Script(input);\n const parsed = guard_exports.IsArray(result) && guard_exports.IsEqual(result.length, 2) ? InstantiateType(context2, State([], []), result[0]) : Never();\n return memory_exports.Update(parsed, {}, options);\n }\n\n // node_modules/typebox/build/value/clean/from_array.mjs\n function FromArray7(context2, type, value) {\n if (!guard_exports.IsArray(value))\n return value;\n return value.map((value2) => FromType19(context2, type.items, value2));\n }\n\n // node_modules/typebox/build/value/clean/from_cyclic.mjs\n function FromCyclic6(context2, type, value) {\n return FromType19({ ...context2, ...type.$defs }, Ref2(type.$ref), value);\n }\n\n // node_modules/typebox/build/value/clean/from_intersect.mjs\n function EvaluateIntersection(context2, type) {\n const additionalProperties = guard_exports.HasPropertyKey(type, \"unevaluatedProperties\") ? { additionalProperties: type.unevaluatedProperties } : {};\n const instantiated = Instantiate(context2, type);\n const evaluated = Evaluate2(instantiated);\n return IsObject3(evaluated) ? With2(evaluated, additionalProperties) : evaluated;\n }\n function FromIntersect6(context2, type, value) {\n const evaluated = EvaluateIntersection(context2, type);\n return FromType19(context2, evaluated, value);\n }\n\n // node_modules/typebox/build/value/clean/additional.mjs\n function GetAdditionalProperties(type) {\n const additionalProperties = guard_exports.HasPropertyKey(type, \"additionalProperties\") ? type.additionalProperties : void 0;\n return additionalProperties;\n }\n\n // node_modules/typebox/build/value/clean/from_object.mjs\n function FromObject11(context2, type, value) {\n if (!guard_exports.IsObject(value) || guard_exports.IsArray(value))\n return value;\n const additionalProperties = GetAdditionalProperties(type);\n for (const key of guard_exports.Keys(value)) {\n if (guard_exports.HasPropertyKey(type.properties, key)) {\n value[key] = FromType19(context2, type.properties[key], value[key]);\n continue;\n }\n const unknownCheck = (\n // 1. additionalProperties: true\n guard_exports.IsBoolean(additionalProperties) && guard_exports.IsEqual(additionalProperties, true) || IsSchema2(additionalProperties) && Check2(context2, additionalProperties, value[key])\n );\n if (unknownCheck) {\n value[key] = FromType19(context2, additionalProperties, value[key]);\n continue;\n }\n delete value[key];\n }\n return value;\n }\n\n // node_modules/typebox/build/value/clean/from_record.mjs\n function FromRecord3(context2, type, value) {\n if (!guard_exports.IsObject(value))\n return value;\n const additionalProperties = GetAdditionalProperties(type);\n const [recordPattern, recordValue] = [new RegExp(RecordPattern(type)), RecordValue(type)];\n for (const key of guard_exports.Keys(value)) {\n if (recordPattern.test(key)) {\n value[key] = FromType19(context2, recordValue, value[key]);\n continue;\n }\n const unknownCheck = (\n // 1. additionalProperties: true\n guard_exports.IsBoolean(additionalProperties) && guard_exports.IsEqual(additionalProperties, true) || IsSchema2(additionalProperties) && Check2(context2, additionalProperties, value[key])\n );\n if (unknownCheck) {\n value[key] = FromType19(context2, additionalProperties, value[key]);\n continue;\n }\n delete value[key];\n }\n return value;\n }\n\n // node_modules/typebox/build/value/clean/from_ref.mjs\n function FromRef5(context2, type, value) {\n return guard_exports.HasPropertyKey(context2, type.$ref) ? FromType19(context2, context2[type.$ref], value) : value;\n }\n\n // node_modules/typebox/build/value/clean/from_tuple.mjs\n function FromTuple5(context2, schema, value) {\n if (!guard_exports.IsArray(value))\n return value;\n const length = Math.min(value.length, schema.items.length);\n for (let index3 = 0; index3 < length; index3++) {\n value[index3] = FromType19(context2, schema.items[index3], value[index3]);\n }\n return guard_exports.IsGreaterThan(value.length, length) ? value.slice(0, length) : value;\n }\n\n // node_modules/typebox/build/value/clone/clone.mjs\n function Clone2(value) {\n return Clone(value);\n }\n\n // node_modules/typebox/build/value/clean/from_union.mjs\n function FromUnion9(context2, type, value) {\n for (const schema of type.anyOf) {\n const clean = FromType19(context2, schema, Clone2(value));\n if (Check2(context2, schema, clean))\n return clean;\n }\n return value;\n }\n\n // node_modules/typebox/build/value/clean/from_type.mjs\n function FromType19(context2, type, value) {\n return IsArray3(type) ? FromArray7(context2, type, value) : IsCyclic(type) ? FromCyclic6(context2, type, value) : IsIntersect(type) ? FromIntersect6(context2, type, value) : IsObject3(type) ? FromObject11(context2, type, value) : IsRecord(type) ? FromRecord3(context2, type, value) : IsRef2(type) ? FromRef5(context2, type, value) : IsTuple(type) ? FromTuple5(context2, type, value) : IsUnion(type) ? FromUnion9(context2, type, value) : value;\n }\n\n // node_modules/typebox/build/value/shared/union_priority_sort.mjs\n function Modifiers(type, next) {\n for (const key of guard_default.Keys(type)) {\n if (guard_default.HasPropertyKey(next, key))\n continue;\n next[key] = type[key];\n }\n return next;\n }\n function FromProperties4(properties) {\n const result = {};\n for (const key of guard_default.Keys(properties))\n result[key] = FromType20(properties[key]);\n return result;\n }\n function FromPriorityTypes(types) {\n return FromTypes6(Priority(types));\n }\n function FromTypes6(types) {\n return types.map((type) => FromType20(type));\n }\n function FromType20(type) {\n const next = IsArray3(type) ? _Array_(FromType20(type.items), ArrayOptions(type)) : IsIntersect(type) ? Intersect(FromTypes6(type.allOf)) : IsUnion(type) ? Union(FromPriorityTypes(type.anyOf)) : IsObject3(type) ? _Object_(FromProperties4(type.properties)) : IsRecord(type) ? Record(RecordKey(type), FromType20(RecordValue(type))) : IsTuple(type) ? Tuple(FromTypes6(type.items)) : type;\n return Modifiers(type, next);\n }\n function UnionPrioritySort(type) {\n const result = FromType20(type);\n return result;\n }\n\n // node_modules/typebox/build/value/clean/clean.mjs\n function Clean(...args) {\n const [context2, type, value] = arguments_exports.Match(args, {\n 3: (context3, type2, value2) => [context3, type2, value2],\n 2: (type2, value2) => [{}, type2, value2]\n });\n const sorted = settings_exports.Get().unionPrioritySort ? UnionPrioritySort(type) : type;\n return FromType19(context2, sorted, value);\n }\n\n // node_modules/typebox/build/value/convert/try/try.mjs\n var try_exports = {};\n __export(try_exports, {\n Fail: () => Fail,\n IsOk: () => IsOk,\n Ok: () => Ok,\n TryArray: () => TryArray,\n TryBigInt: () => TryBigInt,\n TryBoolean: () => TryBoolean,\n TryNull: () => TryNull,\n TryNumber: () => TryNumber,\n TryString: () => TryString,\n TryUndefined: () => TryUndefined\n });\n\n // node_modules/typebox/build/value/convert/try/try_result.mjs\n function IsOk(value) {\n return guard_exports.IsObject(value) && guard_exports.HasPropertyKey(value, \"value\");\n }\n function Ok(value) {\n return { value };\n }\n function Fail() {\n return void 0;\n }\n\n // node_modules/typebox/build/value/convert/try/try_array.mjs\n function TryArray(value) {\n return guard_exports.IsArray(value) ? Ok(value) : Ok([value]);\n }\n\n // node_modules/typebox/build/value/convert/try/try_bigint.mjs\n function FromBoolean2(value) {\n return guard_exports.IsEqual(value, true) ? Ok(BigInt(1)) : Ok(BigInt(0));\n }\n var bigintPattern = /^-?(0|[1-9]\\d*)n$/;\n var decimalPattern = /^-?(0|[1-9]\\d*)\\.\\d+$/;\n var integerPattern = /^-?(0|[1-9]\\d*)$/;\n function IsStringBigIntLike(value) {\n return bigintPattern.test(value);\n }\n function IsStringDecimalLike(value) {\n return decimalPattern.test(value);\n }\n function IsStringIntegerLike(value) {\n return integerPattern.test(value);\n }\n function FromString2(value) {\n const lowercase = value.toLowerCase();\n return IsStringBigIntLike(value) ? Ok(BigInt(value.slice(0, value.length - 1))) : IsStringDecimalLike(value) ? Ok(BigInt(value.split(\".\")[0])) : IsStringIntegerLike(value) ? Ok(BigInt(value)) : guard_exports.IsEqual(lowercase, \"false\") ? Ok(BigInt(0)) : guard_exports.IsEqual(lowercase, \"true\") ? Ok(BigInt(1)) : Fail();\n }\n function TryBigInt(value) {\n return guard_exports.IsBigInt(value) ? Ok(value) : guard_exports.IsBoolean(value) ? FromBoolean2(value) : guard_exports.IsNumber(value) ? Ok(BigInt(Math.trunc(value))) : guard_exports.IsNull(value) ? Ok(BigInt(0)) : guard_exports.IsString(value) ? FromString2(value) : guard_exports.IsUndefined(value) ? Ok(BigInt(0)) : Fail();\n }\n\n // node_modules/typebox/build/value/convert/try/try_boolean.mjs\n function FromBigInt2(value) {\n return guard_exports.IsEqual(value, BigInt(0)) ? Ok(false) : guard_exports.IsEqual(value, BigInt(1)) ? Ok(true) : Fail();\n }\n function FromNumber2(value) {\n return guard_exports.IsEqual(value, 0) ? Ok(false) : guard_exports.IsEqual(value, 1) ? Ok(true) : Fail();\n }\n function FromString3(value) {\n return guard_exports.IsEqual(value.toLowerCase(), \"false\") ? Ok(false) : guard_exports.IsEqual(value.toLowerCase(), \"true\") ? Ok(true) : guard_exports.IsEqual(value, \"0\") ? Ok(false) : guard_exports.IsEqual(value, \"1\") ? Ok(true) : Fail();\n }\n function TryBoolean(value) {\n return guard_exports.IsBigInt(value) ? FromBigInt2(value) : guard_exports.IsBoolean(value) ? Ok(value) : guard_exports.IsNumber(value) ? FromNumber2(value) : guard_exports.IsNull(value) ? Ok(false) : guard_exports.IsString(value) ? FromString3(value) : guard_exports.IsUndefined(value) ? Ok(false) : Fail();\n }\n\n // node_modules/typebox/build/value/convert/try/try_null.mjs\n function FromBigInt3(value) {\n return guard_exports.IsEqual(value, BigInt(0)) ? Ok(null) : Fail();\n }\n function FromBoolean3(value) {\n return guard_exports.IsEqual(value, false) ? Ok(null) : Fail();\n }\n function FromNumber3(value) {\n return guard_exports.IsEqual(value, 0) ? Ok(null) : Fail();\n }\n function FromString4(value) {\n const lowercase = value.toLowerCase();\n const predicate = guard_exports.IsEqual(lowercase, \"undefined\") || guard_exports.IsEqual(lowercase, \"null\") || guard_exports.IsEqual(value, \"\") || guard_exports.IsEqual(value, \"0\");\n return predicate ? Ok(null) : Fail();\n }\n function TryNull(value) {\n return guard_exports.IsBigInt(value) ? FromBigInt3(value) : guard_exports.IsBoolean(value) ? FromBoolean3(value) : guard_exports.IsNumber(value) ? FromNumber3(value) : guard_exports.IsNull(value) ? Ok(null) : guard_exports.IsString(value) ? FromString4(value) : guard_exports.IsUndefined(value) ? Ok(null) : Fail();\n }\n\n // node_modules/typebox/build/value/convert/try/try_number.mjs\n var maxBigInt = BigInt(Number.MAX_SAFE_INTEGER);\n var minBigInt = BigInt(Number.MIN_SAFE_INTEGER);\n function FromBigInt4(value) {\n return value <= maxBigInt && value >= minBigInt ? Ok(Number(value)) : Fail();\n }\n function FromBoolean4(value) {\n return Ok(value ? 1 : 0);\n }\n function FromString5(value) {\n const coerced = +value;\n if (guard_exports.IsNumber(coerced))\n return Ok(coerced);\n const lowercase = value.toLowerCase();\n if (guard_exports.IsEqual(lowercase, \"false\"))\n return Ok(0);\n if (guard_exports.IsEqual(lowercase, \"true\"))\n return Ok(1);\n const result = TryBigInt(value);\n if (IsOk(result))\n return result.value <= maxBigInt && result.value >= minBigInt ? Ok(Number(result.value)) : Fail();\n return Fail();\n }\n function TryNumber(value) {\n return guard_exports.IsBigInt(value) ? FromBigInt4(value) : guard_exports.IsBoolean(value) ? FromBoolean4(value) : guard_exports.IsNumber(value) ? Ok(value) : guard_exports.IsNull(value) ? Ok(0) : guard_exports.IsString(value) ? FromString5(value) : guard_exports.IsUndefined(value) ? Ok(0) : Fail();\n }\n\n // node_modules/typebox/build/value/convert/try/try_string.mjs\n function TryString(value) {\n return guard_exports.IsBigInt(value) ? Ok(value.toString()) : guard_exports.IsBoolean(value) ? Ok(value.toString()) : guard_exports.IsNumber(value) ? Ok(value.toString()) : guard_exports.IsNull(value) ? Ok(\"null\") : guard_exports.IsString(value) ? Ok(value) : guard_exports.IsUndefined(value) ? Ok(\"\") : Fail();\n }\n\n // node_modules/typebox/build/value/convert/try/try_undefined.mjs\n function FromBigInt5(value) {\n return guard_exports.IsEqual(value, BigInt(0)) ? Ok(void 0) : Fail();\n }\n function FromBoolean5(value) {\n return guard_exports.IsEqual(value, false) ? Ok(void 0) : Fail();\n }\n function FromNumber4(value) {\n return guard_exports.IsEqual(value, 0) ? Ok(void 0) : Fail();\n }\n function FromString6(value) {\n const lowercase = value.toLowerCase();\n const predicate = guard_exports.IsEqual(lowercase, \"undefined\") || guard_exports.IsEqual(lowercase, \"null\") || guard_exports.IsEqual(value, \"\") || guard_exports.IsEqual(value, \"0\");\n return predicate ? Ok(void 0) : Fail();\n }\n function TryUndefined(value) {\n return guard_exports.IsBigInt(value) ? FromBigInt5(value) : guard_exports.IsBoolean(value) ? FromBoolean5(value) : guard_exports.IsNumber(value) ? FromNumber4(value) : guard_exports.IsNull(value) ? Ok(void 0) : guard_exports.IsString(value) ? FromString6(value) : guard_exports.IsUndefined(value) ? Ok(value) : Fail();\n }\n\n // node_modules/typebox/build/value/convert/from_array.mjs\n function FromArray8(context2, type, value) {\n const result = try_exports.TryArray(value);\n return result.value.map((value2) => FromType21(context2, type.items, value2));\n }\n\n // node_modules/typebox/build/value/convert/from_bigint.mjs\n function FromBigInt6(_context, _type, value) {\n const result = try_exports.TryBigInt(value);\n return try_exports.IsOk(result) ? result.value : value;\n }\n\n // node_modules/typebox/build/value/convert/from_boolean.mjs\n function FromBoolean6(_context, _type, value) {\n const result = try_exports.TryBoolean(value);\n return try_exports.IsOk(result) ? result.value : value;\n }\n\n // node_modules/typebox/build/value/convert/from_cyclic.mjs\n function FromCyclic7(context2, type, value) {\n return FromType21({ ...context2, ...type.$defs }, Ref2(type.$ref), value);\n }\n\n // node_modules/typebox/build/value/convert/from_enum.mjs\n function FromEnum3(context2, type, value) {\n return FromType21(context2, Evaluate2(type), value);\n }\n\n // node_modules/typebox/build/value/convert/from_integer.mjs\n function FromInteger(_context, _type, value) {\n const result = try_exports.TryNumber(value);\n return try_exports.IsOk(result) ? Math.trunc(result.value) : value;\n }\n\n // node_modules/typebox/build/value/convert/from_intersect.mjs\n function FromIntersect7(context2, type, value) {\n const instantiated = Instantiate(context2, type);\n const evaluated = Evaluate2(instantiated);\n return FromType21(context2, evaluated, value);\n }\n\n // node_modules/typebox/build/value/convert/from_literal.mjs\n function FromLiteralBigInt(_context, type, value) {\n const result = try_exports.TryBigInt(value);\n return try_exports.IsOk(result) && guard_exports.IsEqual(type.const, result.value) ? result.value : value;\n }\n function FromLiteralBoolean(_context, type, value) {\n const result = try_exports.TryBoolean(value);\n return try_exports.IsOk(result) && guard_exports.IsEqual(type.const, result.value) ? result.value : value;\n }\n function FromLiteralNumber(_context, type, value) {\n const result = try_exports.TryNumber(value);\n return try_exports.IsOk(result) && guard_exports.IsEqual(type.const, result.value) ? result.value : value;\n }\n function FromLiteralString(_context, type, value) {\n const result = try_exports.TryString(value);\n return try_exports.IsOk(result) && guard_exports.IsEqual(type.const, result.value) ? result.value : value;\n }\n function FromLiteral6(context2, type, value) {\n if (guard_exports.IsEqual(type.const, value))\n return value;\n return IsLiteralBigInt(type) ? FromLiteralBigInt(context2, type, value) : IsLiteralBoolean(type) ? FromLiteralBoolean(context2, type, value) : IsLiteralNumber(type) ? FromLiteralNumber(context2, type, value) : IsLiteralString(type) ? FromLiteralString(context2, type, value) : Unreachable();\n }\n\n // node_modules/typebox/build/value/convert/from_null.mjs\n function FromNull2(_context, _type, value) {\n const result = try_exports.TryNull(value);\n return try_exports.IsOk(result) ? result.value : value;\n }\n\n // node_modules/typebox/build/value/convert/from_number.mjs\n function FromNumber5(_context, _type, value) {\n const result = try_exports.TryNumber(value);\n return try_exports.IsOk(result) ? result.value : value;\n }\n\n // node_modules/typebox/build/value/convert/from_additional.mjs\n function FromAdditionalProperties(context2, entries, additionalProperties, value) {\n const keys = guard_exports.Keys(value);\n for (const [regexp, _] of entries) {\n for (const key of keys) {\n if (!regexp.test(key)) {\n value[key] = FromType21(context2, additionalProperties, value[key]);\n }\n }\n }\n return value;\n }\n\n // node_modules/typebox/build/value/shared/optional_undefined.mjs\n function IsOptionalUndefined(property, key, value) {\n return IsOptional(property) && guard_exports.IsUndefined(value[key]);\n }\n\n // node_modules/typebox/build/value/convert/from_object.mjs\n function FromProperties5(context2, type, value) {\n const entries = guard_exports.EntriesRegExp(type.properties);\n const keys = guard_exports.Keys(value);\n for (const [regexp, property] of entries) {\n for (const key of keys) {\n if (!regexp.test(key) || IsOptionalUndefined(property, key, value))\n continue;\n value[key] = FromType21(context2, property, value[key]);\n }\n }\n return guard_exports.HasPropertyKey(type, \"additionalProperties\") && guard_exports.IsObject(type.additionalProperties) ? FromAdditionalProperties(context2, entries, type.additionalProperties, value) : value;\n }\n function FromObject12(context2, type, value) {\n return guard_exports.IsObjectNotArray(value) ? FromProperties5(context2, type, value) : value;\n }\n\n // node_modules/typebox/build/value/convert/from_record.mjs\n function FromPatternProperties(context2, type, value) {\n const entries = guard_exports.EntriesRegExp(type.patternProperties);\n const keys = guard_exports.Keys(value);\n for (const [regexp, schema] of entries) {\n for (const key of keys) {\n if (regexp.test(key)) {\n value[key] = FromType21(context2, schema, value[key]);\n }\n }\n }\n return guard_exports.HasPropertyKey(type, \"additionalProperties\") && guard_exports.IsObject(type.additionalProperties) ? FromAdditionalProperties(context2, entries, type.additionalProperties, value) : value;\n }\n function FromRecord4(context2, type, value) {\n return guard_exports.IsObjectNotArray(value) ? FromPatternProperties(context2, type, value) : value;\n }\n\n // node_modules/typebox/build/value/convert/from_ref.mjs\n function FromRef6(context2, type, value) {\n return guard_exports.HasPropertyKey(context2, type.$ref) ? FromType21(context2, context2[type.$ref], value) : value;\n }\n\n // node_modules/typebox/build/value/convert/from_string.mjs\n function FromString7(_context, _type, value) {\n const result = try_exports.TryString(value);\n return try_exports.IsOk(result) ? result.value : value;\n }\n\n // node_modules/typebox/build/value/convert/from_template_literal.mjs\n function FromTemplateLiteral4(context2, type, value) {\n return FromType21(context2, Evaluate2(type), value);\n }\n\n // node_modules/typebox/build/value/convert/from_tuple.mjs\n function FromTuple6(context2, type, value) {\n if (!guard_exports.IsArray(value))\n return value;\n for (let index3 = 0; index3 < Math.min(type.items.length, value.length); index3++) {\n value[index3] = FromType21(context2, type.items[index3], value[index3]);\n }\n return value;\n }\n\n // node_modules/typebox/build/value/convert/from_undefined.mjs\n function FromUndefined2(_context, _type, value) {\n const result = try_exports.TryUndefined(value);\n return try_exports.IsOk(result) ? result.value : value;\n }\n\n // node_modules/typebox/build/value/convert/from_union.mjs\n function FromUnion10(context2, type, value) {\n const matched = type.anyOf.some((type2) => Check2(context2, type2, value));\n if (matched)\n return value;\n const candidates = type.anyOf.map((type2) => FromType21(context2, type2, Clone2(value)));\n const selected = candidates.find((value2) => Check2(context2, type, value2));\n return guard_exports.IsUndefined(selected) ? value : selected;\n }\n\n // node_modules/typebox/build/value/convert/from_void.mjs\n function FromVoid(_context, _type, value) {\n const result = try_exports.TryUndefined(value);\n return try_exports.IsOk(result) ? void 0 : value;\n }\n\n // node_modules/typebox/build/value/convert/from_type.mjs\n function FromType21(context2, type, value) {\n return IsArray3(type) ? FromArray8(context2, type, value) : IsBigInt3(type) ? FromBigInt6(context2, type, value) : IsBoolean4(type) ? FromBoolean6(context2, type, value) : IsCyclic(type) ? FromCyclic7(context2, type, value) : IsEnum2(type) ? FromEnum3(context2, type, value) : IsInteger3(type) ? FromInteger(context2, type, value) : IsIntersect(type) ? FromIntersect7(context2, type, value) : IsLiteral(type) ? FromLiteral6(context2, type, value) : IsNull3(type) ? FromNull2(context2, type, value) : IsNumber4(type) ? FromNumber5(context2, type, value) : IsObject3(type) ? FromObject12(context2, type, value) : IsRecord(type) ? FromRecord4(context2, type, value) : IsRef2(type) ? FromRef6(context2, type, value) : IsString4(type) ? FromString7(context2, type, value) : IsTemplateLiteral(type) ? FromTemplateLiteral4(context2, type, value) : IsTuple(type) ? FromTuple6(context2, type, value) : IsUndefined3(type) ? FromUndefined2(context2, type, value) : IsUnion(type) ? FromUnion10(context2, type, value) : IsVoid(type) ? FromVoid(context2, type, value) : value;\n }\n\n // node_modules/typebox/build/value/convert/convert.mjs\n function Convert(...args) {\n const [context2, type, value] = arguments_exports.Match(args, {\n 3: (context3, type2, value2) => [context3, type2, value2],\n 2: (type2, value2) => [{}, type2, value2]\n });\n return FromType21(context2, type, value);\n }\n\n // node_modules/typebox/build/value/default/from_array.mjs\n function FromArray9(context2, type, value) {\n if (!guard_exports.IsArray(value))\n return value;\n for (let i = 0; i < value.length; i++) {\n value[i] = FromType22(context2, type.items, value[i]);\n }\n return value;\n }\n\n // node_modules/typebox/build/value/default/from_cyclic.mjs\n function FromCyclic8(context2, type, value) {\n return FromType22({ ...context2, ...type.$defs }, Ref2(type.$ref), value);\n }\n\n // node_modules/typebox/build/value/default/from_default.mjs\n function FromDefault(type, value) {\n if (!guard_exports.IsUndefined(value))\n return value;\n return guard_exports.IsFunction(type.default) ? type.default() : Clone2(type.default);\n }\n\n // node_modules/typebox/build/value/default/from_intersect.mjs\n function FromIntersect8(context2, type, value) {\n const instantiated = Instantiate(context2, type);\n const evaluated = Evaluate2(instantiated);\n return FromType22(context2, evaluated, value);\n }\n\n // node_modules/typebox/build/value/default/from_object.mjs\n function FromObject13(context2, type, value) {\n if (!guard_exports.IsObject(value))\n return value;\n const knownPropertyKeys = guard_exports.Keys(type.properties);\n for (const key of knownPropertyKeys) {\n const propertyValue = FromType22(context2, type.properties[key], value[key]);\n const isUnassignableUndefined = guard_exports.IsUndefined(propertyValue) && (IsOptional(type.properties[key]) || !guard_exports.HasPropertyKey(type.properties[key], \"default\"));\n if (isUnassignableUndefined)\n continue;\n value[key] = propertyValue;\n }\n if (!IsAdditionalProperties(type) || guard_exports.IsBoolean(type.additionalProperties))\n return value;\n for (const key of guard_exports.Keys(value)) {\n if (knownPropertyKeys.includes(key))\n continue;\n value[key] = FromType22(context2, type.additionalProperties, value[key]);\n }\n return value;\n }\n\n // node_modules/typebox/build/value/default/from_record.mjs\n function FromRecord5(context2, type, value) {\n if (!guard_exports.IsObject(value))\n return value;\n const [recordKey, recordValue] = [new RegExp(RecordPattern(type)), RecordValue(type)];\n for (const key of guard_exports.Keys(value)) {\n if (!(recordKey.test(key) && IsDefault(recordValue)))\n continue;\n value[key] = FromType22(context2, recordValue, value[key]);\n }\n if (!IsAdditionalProperties(type))\n return value;\n for (const key of guard_exports.Keys(value)) {\n if (recordKey.test(key))\n continue;\n value[key] = FromType22(context2, type.additionalProperties, value[key]);\n }\n return value;\n }\n\n // node_modules/typebox/build/value/default/from_ref.mjs\n function FromRef7(context2, type, value) {\n return guard_exports.HasPropertyKey(context2, type.$ref) ? FromType22(context2, context2[type.$ref], value) : value;\n }\n\n // node_modules/typebox/build/value/default/from_tuple.mjs\n function FromTuple7(context2, schema, value) {\n if (!guard_exports.IsArray(value))\n return value;\n const [items, max] = [schema.items, Math.max(schema.items.length, value.length)];\n for (let i = 0; i < max; i++) {\n if (i < items.length)\n value[i] = FromType22(context2, items[i], value[i]);\n }\n return value;\n }\n\n // node_modules/typebox/build/value/default/from_union.mjs\n function FromUnion11(context2, schema, value) {\n for (const inner of schema.anyOf) {\n const result = FromType22(context2, inner, Clone2(value));\n if (Check2(context2, inner, result)) {\n return result;\n }\n }\n return value;\n }\n\n // node_modules/typebox/build/value/default/from_type.mjs\n function FromType22(context2, type, value) {\n const defaulted = IsDefault(type) ? FromDefault(type, value) : value;\n return IsArray3(type) ? FromArray9(context2, type, defaulted) : IsCyclic(type) ? FromCyclic8(context2, type, defaulted) : IsIntersect(type) ? FromIntersect8(context2, type, defaulted) : IsObject3(type) ? FromObject13(context2, type, defaulted) : IsRecord(type) ? FromRecord5(context2, type, defaulted) : IsRef2(type) ? FromRef7(context2, type, defaulted) : IsTuple(type) ? FromTuple7(context2, type, defaulted) : IsUnion(type) ? FromUnion11(context2, type, defaulted) : defaulted;\n }\n\n // node_modules/typebox/build/value/default/default.mjs\n function Default(...args) {\n const [context2, type, value] = arguments_exports.Match(args, {\n 3: (context3, type2, value2) => [context3, type2, value2],\n 2: (type2, value2) => [{}, type2, value2]\n });\n return FromType22(context2, type, value);\n }\n\n // node_modules/typebox/build/value/pipeline/pipeline.mjs\n function Pipeline(pipeline) {\n return (...args) => {\n const [context2, type, value] = arguments_exports.Match(args, {\n 3: (context3, type2, value2) => [context3, type2, value2],\n 2: (type2, value2) => [{}, type2, value2]\n });\n return pipeline.reduce((result, func) => func(context2, type, result), value);\n };\n }\n\n // node_modules/typebox/build/value/codec/callback.mjs\n function Decode3(_context, type, value) {\n return type[\"~codec\"].decode(value);\n }\n function Encode3(_context, type, value) {\n return type[\"~codec\"].encode(value);\n }\n function Callback(direction, context2, type, value) {\n if (!IsCodec(type))\n return value;\n return guard_exports.IsEqual(direction, \"Decode\") ? Decode3(context2, type, value) : Encode3(context2, type, value);\n }\n\n // node_modules/typebox/build/value/codec/from_array.mjs\n function Decode4(direction, context2, type, value) {\n if (!guard_exports.IsArray(value))\n return value;\n for (let i = 0; i < value.length; i++) {\n value[i] = FromType23(direction, context2, type.items, value[i]);\n }\n return Callback(direction, context2, type, value);\n }\n function Encode4(direction, context2, type, value) {\n const exterior = Callback(direction, context2, type, value);\n if (!guard_exports.IsArray(exterior))\n return exterior;\n for (let i = 0; i < exterior.length; i++) {\n exterior[i] = FromType23(direction, context2, type.items, exterior[i]);\n }\n return exterior;\n }\n function FromArray10(direction, context2, type, value) {\n return guard_exports.IsEqual(direction, \"Decode\") ? Decode4(direction, context2, type, value) : Encode4(direction, context2, type, value);\n }\n\n // node_modules/typebox/build/value/codec/from_cyclic.mjs\n function FromCyclic9(direction, context2, type, value) {\n value = FromType23(direction, { ...context2, ...type.$defs }, Ref2(type.$ref), value);\n return Callback(direction, context2, type, value);\n }\n\n // node_modules/typebox/build/value/codec/from_intersect.mjs\n function MergeInteriors(interiors) {\n return interiors.reduce((results, interior) => ({ ...results, ...interior }), {});\n }\n function NonMatchingInterior(value, interiors) {\n for (const interior of interiors)\n if (!guard_exports.IsDeepEqual(value, interior))\n return interior;\n return value;\n }\n function Decode5(direction, context2, type, value) {\n if (guard_exports.IsEqual(type.allOf.length, 0))\n return Callback(direction, context2, type, value);\n const interiors = type.allOf.map((schema) => FromType23(direction, context2, schema, Clean(schema, Clone2(value))));\n const structural = interiors.every((result) => guard_exports.IsObject(result));\n const exterior = structural ? MergeInteriors(interiors) : NonMatchingInterior(value, interiors);\n return Callback(direction, context2, type, exterior);\n }\n function Encode5(direction, context2, type, value) {\n if (guard_exports.IsEqual(type.allOf.length, 0))\n return Callback(direction, context2, type, value);\n const exterior = Callback(direction, context2, type, value);\n const interiors = type.allOf.map((schema) => FromType23(direction, context2, schema, Clean(schema, Clone2(exterior))));\n const structural = interiors.every((result) => guard_exports.IsObject(result));\n if (structural)\n return MergeInteriors(interiors);\n return NonMatchingInterior(exterior, interiors);\n }\n function FromIntersect9(direction, context2, type, value) {\n return guard_exports.IsEqual(direction, \"Decode\") ? Decode5(direction, context2, type, value) : Encode5(direction, context2, type, value);\n }\n\n // node_modules/typebox/build/value/codec/from_object.mjs\n function Decode6(direction, context2, type, value) {\n if (!guard_exports.IsObjectNotArray(value))\n return value;\n for (const key of guard_exports.Keys(type.properties)) {\n if (!guard_exports.HasPropertyKey(value, key) || IsOptionalUndefined(type.properties[key], key, value))\n continue;\n value[key] = FromType23(direction, context2, type.properties[key], value[key]);\n }\n return Callback(direction, context2, type, value);\n }\n function Encode6(direction, context2, type, value) {\n const exterior = Callback(direction, context2, type, value);\n if (!guard_exports.IsObjectNotArray(exterior))\n return exterior;\n for (const key of guard_exports.Keys(type.properties)) {\n if (!guard_exports.HasPropertyKey(exterior, key) || IsOptionalUndefined(type.properties[key], key, exterior))\n continue;\n exterior[key] = FromType23(direction, context2, type.properties[key], exterior[key]);\n }\n return exterior;\n }\n function FromObject14(direction, context2, type, value) {\n return guard_exports.IsEqual(direction, \"Decode\") ? Decode6(direction, context2, type, value) : Encode6(direction, context2, type, value);\n }\n\n // node_modules/typebox/build/value/codec/from_record.mjs\n function Decode7(direction, context2, type, value) {\n if (!guard_exports.IsObjectNotArray(value))\n return value;\n const regexp = new RegExp(RecordPattern(type));\n for (const key of guard_exports.Keys(value)) {\n if (!regexp.test(key))\n continue;\n value[key] = FromType23(direction, context2, RecordValue(type), value[key]);\n }\n return Callback(direction, context2, type, value);\n }\n function Encode7(direction, context2, type, value) {\n const exterior = Callback(direction, context2, type, value);\n if (!guard_exports.IsObjectNotArray(exterior))\n return exterior;\n const regexp = new RegExp(RecordPattern(type));\n for (const key of guard_exports.Keys(exterior)) {\n if (!regexp.test(key))\n continue;\n exterior[key] = FromType23(direction, context2, RecordValue(type), exterior[key]);\n }\n return exterior;\n }\n function FromRecord6(direction, context2, type, value) {\n return guard_exports.IsEqual(direction, \"Decode\") ? Decode7(direction, context2, type, value) : Encode7(direction, context2, type, value);\n }\n\n // node_modules/typebox/build/value/codec/from_ref.mjs\n function ResolveRef2(direction, context2, type, value) {\n return guard_exports.HasPropertyKey(context2, type.$ref) ? FromType23(direction, context2, context2[type.$ref], value) : value;\n }\n function FromRef8(direction, context2, type, value) {\n return guard_exports.IsEqual(direction, \"Decode\") ? Callback(direction, context2, type, ResolveRef2(direction, context2, type, value)) : ResolveRef2(direction, context2, type, Callback(direction, context2, type, value));\n }\n\n // node_modules/typebox/build/value/codec/from_tuple.mjs\n function Decode8(direction, context2, type, value) {\n if (!guard_exports.IsArray(value))\n return value;\n for (let i = 0; i < Math.min(type.items.length, value.length); i++) {\n value[i] = FromType23(direction, context2, type.items[i], value[i]);\n }\n return Callback(direction, context2, type, value);\n }\n function Encode8(direction, context2, type, value) {\n const exterior = Callback(direction, context2, type, value);\n if (!guard_exports.IsArray(exterior))\n return value;\n for (let i = 0; i < Math.min(type.items.length, exterior.length); i++) {\n exterior[i] = FromType23(direction, context2, type.items[i], exterior[i]);\n }\n return exterior;\n }\n function FromTuple8(direction, context2, type, value) {\n return guard_exports.IsEqual(direction, \"Decode\") ? Decode8(direction, context2, type, value) : Encode8(direction, context2, type, value);\n }\n\n // node_modules/typebox/build/value/codec/from_union.mjs\n function Decode9(direction, context2, type, value) {\n for (const schema of type.anyOf) {\n if (!Check2(context2, schema, value))\n continue;\n const variant = FromType23(direction, context2, schema, value);\n return Callback(direction, context2, type, variant);\n }\n return value;\n }\n function Encode9(direction, context2, type, value) {\n const exterior = Callback(direction, context2, type, value);\n for (const schema of type.anyOf) {\n const variant = FromType23(direction, context2, schema, Clone2(exterior));\n if (!Check2(context2, schema, variant))\n continue;\n return variant;\n }\n return exterior;\n }\n function FromUnion12(direction, context2, type, value) {\n return guard_exports.IsEqual(direction, \"Decode\") ? Decode9(direction, context2, type, value) : Encode9(direction, context2, type, value);\n }\n\n // node_modules/typebox/build/value/codec/from_type.mjs\n function FromType23(direction, context2, type, value) {\n return IsArray3(type) ? FromArray10(direction, context2, type, value) : IsCyclic(type) ? FromCyclic9(direction, context2, type, value) : IsIntersect(type) ? FromIntersect9(direction, context2, type, value) : IsObject3(type) ? FromObject14(direction, context2, type, value) : IsRecord(type) ? FromRecord6(direction, context2, type, value) : IsRef2(type) ? FromRef8(direction, context2, type, value) : IsTuple(type) ? FromTuple8(direction, context2, type, value) : IsUnion(type) ? FromUnion12(direction, context2, type, value) : Callback(direction, context2, type, value);\n }\n\n // node_modules/typebox/build/value/codec/decode.mjs\n var DecodeError = class extends AssertError {\n constructor(value, errors) {\n super(\"Decode\", value, errors);\n }\n };\n function Assert2(context2, type, value) {\n if (!Check2(context2, type, value))\n throw new DecodeError(value, Errors2(context2, type, value));\n return value;\n }\n function DecodeUnsafe(context2, type, value) {\n const sorted = settings_exports.Get().unionPrioritySort ? UnionPrioritySort(type) : type;\n return FromType23(\"Decode\", context2, sorted, value);\n }\n var Decoder = Pipeline([\n (_context, _type, value) => Clone2(value),\n (context2, type, value) => Default(context2, type, value),\n (context2, type, value) => Convert(context2, type, value),\n (context2, type, value) => Clean(context2, type, value),\n (context2, type, value) => Assert2(context2, type, value),\n (context2, type, value) => DecodeUnsafe(context2, type, value)\n ]);\n function Decode10(...args) {\n const [context2, type, value] = arguments_exports.Match(args, {\n 3: (context3, type2, value2) => [context3, type2, value2],\n 2: (type2, value2) => [{}, type2, value2]\n });\n return Decoder(context2, type, value);\n }\n\n // node_modules/typebox/build/value/codec/encode.mjs\n var EncodeError = class extends AssertError {\n constructor(value, errors) {\n super(\"Encode\", value, errors);\n }\n };\n function Assert3(context2, type, value) {\n if (!Check2(context2, type, value))\n throw new EncodeError(value, Errors2(context2, type, value));\n return value;\n }\n function EncodeUnsafe(context2, type, value) {\n const sorted = settings_exports.Get().unionPrioritySort ? UnionPrioritySort(type) : type;\n return FromType23(\"Encode\", context2, sorted, value);\n }\n var Encoder = Pipeline([\n (_context, _type, value) => Clone2(value),\n (context2, type, value) => EncodeUnsafe(context2, type, value),\n (context2, type, value) => Default(context2, type, value),\n (context2, type, value) => Convert(context2, type, value),\n (context2, type, value) => Clean(context2, type, value),\n (context2, type, value) => Assert3(context2, type, value)\n ]);\n function Encode10(...args) {\n const [context2, type, value] = arguments_exports.Match(args, {\n 3: (context3, type2, value2) => [context3, type2, value2],\n 2: (type2, value2) => [{}, type2, value2]\n });\n return Encoder(context2, type, value);\n }\n\n // node_modules/typebox/build/value/codec/has.mjs\n function FromArray11(context2, type) {\n return IsCodec(type) || FromType24(context2, type.items);\n }\n function FromCyclic10(context2, type) {\n return IsCodec(type) || FromRef9({ ...context2, ...type.$defs }, Ref2(type.$ref));\n }\n function FromIntersect10(context2, type) {\n return IsCodec(type) || type.allOf.some((type2) => FromType24(context2, type2));\n }\n function FromObject15(context2, type) {\n return IsCodec(type) || guard_exports.Keys(type.properties).some((key) => {\n return FromType24(context2, type.properties[key]);\n });\n }\n function FromRecord7(context2, type) {\n return IsCodec(type) || FromType24(context2, RecordValue(type));\n }\n function FromRef9(context2, type) {\n if (visited.has(type.$ref))\n return false;\n visited.add(type.$ref);\n return IsCodec(type) || guard_exports.HasPropertyKey(context2, type.$ref) && FromType24(context2, context2[type.$ref]);\n }\n function FromTuple9(context2, type) {\n return IsCodec(type) || type.items.some((type2) => FromType24(context2, type2));\n }\n function FromUnion13(context2, type) {\n return IsCodec(type) || type.anyOf.some((type2) => FromType24(context2, type2));\n }\n function FromType24(context2, type) {\n return IsArray3(type) ? FromArray11(context2, type) : IsCyclic(type) ? FromCyclic10(context2, type) : IsIntersect(type) ? FromIntersect10(context2, type) : IsObject3(type) ? FromObject15(context2, type) : IsRecord(type) ? FromRecord7(context2, type) : IsRef2(type) ? FromRef9(context2, type) : IsTuple(type) ? FromTuple9(context2, type) : IsUnion(type) ? FromUnion13(context2, type) : IsCodec(type);\n }\n var visited = /* @__PURE__ */ new Set();\n function HasCodec(...args) {\n const [context2, type] = arguments_exports.Match(args, {\n 2: (context3, type2) => [context3, type2],\n 1: (type2) => [{}, type2]\n });\n visited.clear();\n return FromType24(context2, type);\n }\n\n // node_modules/typebox/build/value/create/error.mjs\n var CreateError = class extends Error {\n constructor(type, message) {\n super(message);\n this.type = type;\n }\n };\n\n // node_modules/typebox/build/value/create/from_default.mjs\n function FromDefault2(_context, schema) {\n return guard_exports.IsFunction(schema.default) ? schema.default(schema) : guard_exports.IsObject(schema.default) ? Clone2(schema.default) : schema.default;\n }\n\n // node_modules/typebox/build/value/create/from_array.mjs\n function FromArray12(context2, type) {\n if (IsUniqueItems(type) && !IsDefault(type))\n throw new CreateError(type, \"Arrays with uniqueItems constraints must specify a default annotation\");\n const length = IsMinItems(type) ? type.minItems : 0;\n return Array.from({ length }, () => FromType25(context2, type.items));\n }\n\n // node_modules/typebox/build/value/create/from_bigint.mjs\n function FromBigInt7(_context, type) {\n return IsExclusiveMinimum(type) ? BigInt(type.exclusiveMinimum) + BigInt(1) : IsMinimum(type) ? BigInt(type.minimum) : BigInt(0);\n }\n\n // node_modules/typebox/build/value/create/from_boolean.mjs\n function FromBoolean7(_context, _type) {\n return false;\n }\n\n // node_modules/typebox/build/value/create/from_constructor.mjs\n function FromConstructor2(context2, type) {\n const instanceType = FromType25(context2, type.instanceType);\n return class {\n constructor() {\n Object.assign(this, instanceType);\n }\n };\n }\n\n // node_modules/typebox/build/value/create/from_cyclic.mjs\n function FromCyclic11(context2, type) {\n return FromType25({ ...context2, ...type.$defs }, Ref2(type.$ref));\n }\n\n // node_modules/typebox/build/value/create/from_enum.mjs\n function FromEnum4(context2, type) {\n return FromType25(context2, Evaluate2(type));\n }\n\n // node_modules/typebox/build/value/create/from_function.mjs\n function FromFunction2(context2, type) {\n const returnType = FromType25(context2, type.returnType);\n return () => returnType;\n }\n\n // node_modules/typebox/build/value/create/from_integer.mjs\n function FromInteger2(_context, type) {\n return IsExclusiveMinimum(type) && guard_exports.IsNumber(type.exclusiveMinimum) ? type.exclusiveMinimum + 1 : IsMinimum(type) ? type.minimum : 0;\n }\n\n // node_modules/typebox/build/value/create/from_intersect.mjs\n function FromIntersect11(context2, type) {\n const instantiated = Instantiate(context2, type);\n const evaluated = Evaluate2(instantiated);\n return FromType25(context2, evaluated);\n }\n\n // node_modules/typebox/build/value/create/from_literal.mjs\n function FromLiteral7(_context, type) {\n return type.const;\n }\n\n // node_modules/typebox/build/value/create/from_never.mjs\n function FromNever(_context, type) {\n throw new CreateError(type, \"Cannot create TNever types\");\n }\n\n // node_modules/typebox/build/value/create/from_null.mjs\n function FromNull3(_context, _type) {\n return null;\n }\n\n // node_modules/typebox/build/value/create/from_number.mjs\n function FromNumber6(_context, type) {\n return IsExclusiveMinimum(type) && guard_exports.IsNumber(type.exclusiveMinimum) ? type.exclusiveMinimum + 1 : IsMinimum(type) ? type.minimum : 0;\n }\n\n // node_modules/typebox/build/value/create/from_object.mjs\n function FromObject16(context2, type) {\n const required = guard_exports.IsUndefined(type.required) ? [] : type.required;\n return required.reduce((result, key) => {\n return { ...result, [key]: FromType25(context2, type.properties[key]) };\n }, {});\n }\n\n // node_modules/typebox/build/value/create/from_record.mjs\n function FromRecord8(_context, type) {\n if (IsMinProperties(type) && !IsDefault(type))\n throw new CreateError(type, \"Record with the minProperties constraint must have a default annotation\");\n return {};\n }\n\n // node_modules/typebox/build/value/create/from_ref.mjs\n function FromRef10(context2, type) {\n return guard_exports.HasPropertyKey(context2, type.$ref) ? FromType25(context2, context2[type.$ref]) : (() => {\n throw new CreateError(type, \"Unable to deref Ref\");\n })();\n }\n\n // node_modules/typebox/build/value/create/from_string.mjs\n function FromString8(_context, type) {\n const needsDefault = (IsPattern(type) || IsFormat(type)) && !IsDefault(type);\n if (needsDefault)\n throw Error(\"Strings with format or pattern constraints must specify default\");\n const minLength = IsMinLength4(type) ? type.minLength : 0;\n return \"\".padEnd(minLength);\n }\n\n // node_modules/typebox/build/value/create/from_symbol.mjs\n function FromSymbol2(_context, _type) {\n return /* @__PURE__ */ Symbol();\n }\n\n // node_modules/typebox/build/value/create/from_template_literal.mjs\n function FromTemplateLiteral5(context2, type) {\n const decoded = TemplateLiteralDecode(type.pattern);\n if (IsString4(decoded))\n throw new CreateError(type, \"Unable to create TemplateLiteral due to infinite type expansion\");\n return FromType25(context2, decoded);\n }\n\n // node_modules/typebox/build/value/create/from_tuple.mjs\n function FromTuple10(context2, type) {\n return Array.from({ length: type.minItems }, (_, i) => FromType25(context2, type.items[i]));\n }\n\n // node_modules/typebox/build/value/create/from_undefined.mjs\n function FromUndefined3(_context, _type) {\n return void 0;\n }\n\n // node_modules/typebox/build/value/create/from_union.mjs\n function FromUnion14(context2, type) {\n if (guard_exports.IsEqual(type.anyOf.length, 0)) {\n throw Error(\"Unable to create Union with no variants\");\n }\n return FromType25(context2, type.anyOf[0]);\n }\n\n // node_modules/typebox/build/value/create/from_void.mjs\n function FromVoid2(_context, _type) {\n return void 0;\n }\n\n // node_modules/typebox/build/value/create/from_type.mjs\n function FromType25(context2, type) {\n return (\n // -----------------------------------------------------\n // Default\n // -----------------------------------------------------\n IsDefault(type) ? FromDefault2(context2, type) : (\n // -----------------------------------------------------\n // Types\n // -----------------------------------------------------\n IsArray3(type) ? FromArray12(context2, type) : IsBigInt3(type) ? FromBigInt7(context2, type) : IsBoolean4(type) ? FromBoolean7(context2, type) : IsConstructor3(type) ? FromConstructor2(context2, type) : IsCyclic(type) ? FromCyclic11(context2, type) : IsEnum2(type) ? FromEnum4(context2, type) : IsFunction3(type) ? FromFunction2(context2, type) : IsInteger3(type) ? FromInteger2(context2, type) : IsIntersect(type) ? FromIntersect11(context2, type) : IsLiteral(type) ? FromLiteral7(context2, type) : IsNever(type) ? FromNever(context2, type) : IsNull3(type) ? FromNull3(context2, type) : IsNumber4(type) ? FromNumber6(context2, type) : IsObject3(type) ? FromObject16(context2, type) : IsRecord(type) ? FromRecord8(context2, type) : IsRef2(type) ? FromRef10(context2, type) : IsString4(type) ? FromString8(context2, type) : IsSymbol3(type) ? FromSymbol2(context2, type) : IsTemplateLiteral(type) ? FromTemplateLiteral5(context2, type) : IsTuple(type) ? FromTuple10(context2, type) : IsUndefined3(type) ? FromUndefined3(context2, type) : IsUnion(type) ? FromUnion14(context2, type) : IsVoid(type) ? FromVoid2(context2, type) : void 0\n )\n );\n }\n\n // node_modules/typebox/build/value/create/create.mjs\n function Create2(...args) {\n const [context2, type] = arguments_exports.Match(args, {\n 2: (context3, type2) => [context3, type2],\n 1: (type2) => [{}, type2]\n });\n return FromType25(context2, type);\n }\n\n // node_modules/typebox/build/value/equal/equal.mjs\n function Equal(left, right) {\n return guard_exports.IsDeepEqual(left, right);\n }\n\n // node_modules/typebox/build/value/hash/hash.mjs\n function Hash2(value) {\n return hash_exports.Hash(value);\n }\n\n // node_modules/typebox/build/value/parse/parse.mjs\n var ParseError = class extends AssertError {\n constructor(value, errors) {\n super(\"Parse\", value, errors);\n }\n };\n function Assert4(context2, type, value) {\n if (!Check2(context2, type, value))\n throw new ParseError(value, Errors2(context2, type, value));\n return value;\n }\n var Parser = Pipeline([\n (_context, _type, value) => Clone2(value),\n (context2, type, value) => Default(context2, type, value),\n (context2, type, value) => Convert(context2, type, value),\n (context2, type, value) => Clean(context2, type, value),\n (context2, type, value) => Assert4(context2, type, value)\n ]);\n function Parse(...args) {\n const [context2, type, value] = arguments_exports.Match(args, {\n 3: (context3, type2, value2) => [context3, type2, value2],\n 2: (type2, value2) => [{}, type2, value2]\n });\n const checked = Check2(context2, type, value);\n if (checked)\n return value;\n if (settings_exports.Get().correctiveParse)\n return Parser(context2, type, value);\n throw new ParseError(value, Errors2(context2, type, value));\n }\n\n // node_modules/typebox/build/value/delta/diff.mjs\n function CreateUpdate(path, value) {\n return { type: \"update\", path, value };\n }\n function CreateInsert(path, value) {\n return { type: \"insert\", path, value };\n }\n function CreateDelete(path) {\n return { type: \"delete\", path };\n }\n function AssertCanDiffObject(value) {\n if (guard_exports.IsObject(value) && guard_exports.IsEqual(guard_exports.Symbols(value).length, 0))\n return;\n throw new Error(\"Cannot create diffs for objects with symbols keys\");\n }\n function* FromObject17(path, left, right) {\n if (!guard_exports.IsObject(right) || guard_exports.IsArray(right))\n return yield CreateUpdate(path, right);\n AssertCanDiffObject(left);\n AssertCanDiffObject(right);\n const leftKeys = guard_exports.Keys(left);\n const rightKeys = guard_exports.Keys(right);\n for (const key of rightKeys) {\n if (guard_exports.HasPropertyKey(left, key))\n continue;\n if (guard_exports.IsUnsafePropertyKey(key))\n continue;\n yield CreateInsert(`${path}/${key}`, right[key]);\n }\n for (const key of leftKeys) {\n if (!guard_exports.HasPropertyKey(right, key))\n continue;\n if (guard_exports.IsUnsafePropertyKey(key))\n continue;\n if (Equal(left, right))\n continue;\n yield* FromValue4(`${path}/${key}`, left[key], right[key]);\n }\n for (const key of leftKeys) {\n if (guard_exports.HasPropertyKey(right, key))\n continue;\n if (guard_exports.IsUnsafePropertyKey(key))\n continue;\n yield CreateDelete(`${path}/${key}`);\n }\n }\n function* FromArray13(path, left, right) {\n if (!guard_exports.IsArray(right))\n return yield CreateUpdate(path, right);\n for (let i = 0; i < Math.min(left.length, right.length); i++) {\n yield* FromValue4(`${path}/${i}`, left[i], right[i]);\n }\n for (let i = 0; i < right.length; i++) {\n if (i < left.length)\n continue;\n yield CreateInsert(`${path}/${i}`, right[i]);\n }\n for (let i = left.length - 1; i >= 0; i--) {\n if (i < right.length)\n continue;\n yield CreateDelete(`${path}/${i}`);\n }\n }\n function* FromTypedArray2(path, left, right) {\n const typeLeft = globalThis.Object.getPrototypeOf(left).constructor.name;\n const typeRight = globalThis.Object.getPrototypeOf(right).constructor.name;\n const predicate = globals_exports.IsTypeArray(right) && guard_exports.IsEqual(left.length, right.length) && guard_exports.IsEqual(typeLeft, typeRight);\n if (predicate) {\n for (let index3 = 0; index3 < Math.min(left.length, right.length); index3++) {\n yield* FromValue4(`${path}/${index3}`, left[index3], right[index3]);\n }\n } else {\n return yield CreateUpdate(path, right);\n }\n }\n function* FromUnknown(path, left, right) {\n if (left === right)\n return;\n yield CreateUpdate(path, right);\n }\n function* FromValue4(path, left, right) {\n return globals_exports.IsTypeArray(left) ? yield* FromTypedArray2(path, left, right) : guard_exports.IsArray(left) ? yield* FromArray13(path, left, right) : guard_exports.IsObject(left) ? yield* FromObject17(path, left, right) : yield* FromUnknown(path, left, right);\n }\n function Diff(current, next) {\n return [...FromValue4(\"\", current, next)];\n }\n\n // node_modules/typebox/build/value/delta/edit.mjs\n var Insert2 = _Object_({\n type: Literal(\"insert\"),\n path: String2(),\n value: Unknown()\n });\n var Update2 = Object({\n type: Literal(\"update\"),\n path: String2(),\n value: Unknown()\n });\n var Delete2 = _Object_({\n type: Literal(\"delete\"),\n path: String2()\n });\n var Edit = Union([Insert2, Update2, Delete2]);\n\n // node_modules/typebox/build/value/delta/patch.mjs\n function IsRoot(edits) {\n return edits.length > 0 && edits[0].path === \"\" && edits[0].type === \"update\";\n }\n function IsEmpty(edits) {\n return edits.length === 0;\n }\n function Patch(current, edits) {\n if (IsRoot(edits))\n return Clone2(edits[0].value);\n if (IsEmpty(edits))\n return Clone2(current);\n const clone2 = Clone2(current);\n for (const edit of edits) {\n switch (edit.type) {\n case \"insert\": {\n pointer_exports.Set(clone2, edit.path, edit.value);\n break;\n }\n case \"update\": {\n pointer_exports.Set(clone2, edit.path, edit.value);\n break;\n }\n case \"delete\": {\n pointer_exports.Delete(clone2, edit.path);\n break;\n }\n }\n }\n return clone2;\n }\n\n // node_modules/typebox/build/value/repair/error.mjs\n var RepairError = class extends Error {\n constructor(context2, type, value, message) {\n super(message);\n this.context = context2;\n this.type = type;\n this.value = value;\n }\n };\n\n // node_modules/typebox/build/value/repair/from_array.mjs\n function MakeUnique(values) {\n const [hashes, result] = [/* @__PURE__ */ new Set(), []];\n for (const value of values) {\n const hash = Hash2(value);\n if (hashes.has(hash))\n continue;\n hashes.add(hash);\n result.push(value);\n }\n return result;\n }\n function FromArray14(context2, type, value) {\n if (Check2(context2, type, value))\n return value;\n const created = guard_exports.IsArray(value) ? value : Create2(context2, type);\n const minimum = IsMinItems(type) && created.length < type.minItems ? [...created, ...Array.from({ length: type.minItems - created.length }, () => Create2(context2, type))] : created;\n const maximum = IsMaxItems(type) && minimum.length > type.maxItems ? minimum.slice(0, type.maxItems) : minimum;\n const repaired = maximum.map((value2) => FromType26(context2, type.items, value2));\n if (!IsUniqueItems(type) || IsUniqueItems(type) && !guard_exports.IsEqual(type.uniqueItems, true))\n return repaired;\n const unique = MakeUnique(repaired);\n if (!Check2(context2, type, unique))\n throw new RepairError(context2, type, value, \"Failed to repair Array due to uniqueItems constraint\");\n return unique;\n }\n\n // node_modules/typebox/build/value/repair/from_enum.mjs\n function FromEnum5(context2, type, value) {\n return FromType26(context2, Evaluate2(type), value);\n }\n\n // node_modules/typebox/build/value/repair/from_intersect.mjs\n function FromIntersect12(context2, type, value) {\n const instantiated = Instantiate(context2, type);\n const evaluated = Evaluate2(instantiated);\n return FromType26(context2, evaluated, value);\n }\n\n // node_modules/typebox/build/value/repair/from_object.mjs\n function FromObject18(context2, type, value) {\n if (Check2(context2, type, value))\n return value;\n if (!guard_exports.IsObjectNotArray(value))\n return Create2(context2, type);\n const required = new Set(guard_exports.IsUndefined(type.required) ? [] : type.required);\n const result = {};\n for (const [key, schema] of guard_exports.Entries(type.properties)) {\n if (!required.has(key) && guard_exports.IsUndefined(value[key]))\n continue;\n result[key] = key in value ? FromType26(context2, schema, value[key]) : Create2(context2, schema);\n }\n const evaluatedKeys = guard_exports.Keys(type.properties);\n if (IsAdditionalProperties(type) && guard_exports.IsObject(type.additionalProperties)) {\n for (const key of guard_exports.Keys(value)) {\n if (evaluatedKeys.includes(key))\n continue;\n result[key] = FromType26(context2, type.additionalProperties, value[key]);\n }\n }\n return result;\n }\n\n // node_modules/typebox/build/value/repair/from_record.mjs\n function FromRecord9(context2, type, value) {\n if (Check2(context2, type, value))\n return value;\n if (guard_exports.IsNull(value) || !guard_exports.IsObject(value) || guard_exports.IsArray(value))\n return Create2(context2, type);\n const recordKey = new RegExp(RecordPattern(type));\n const recordValue = RecordValue(type);\n const evaluatedKeys = /* @__PURE__ */ new Set();\n const result = {};\n for (const [key, value_] of guard_exports.Entries(value)) {\n if (!recordKey.test(key))\n continue;\n result[key] = FromType26(context2, recordValue, value_);\n evaluatedKeys.add(key);\n }\n if (IsAdditionalProperties(type)) {\n for (const key of guard_exports.Keys(value)) {\n if (evaluatedKeys.has(key))\n continue;\n result[key] = FromType26(context2, type.additionalProperties, value[key]);\n }\n }\n return result;\n }\n\n // node_modules/typebox/build/value/repair/from_ref.mjs\n function FromRef11(context2, type, value) {\n return guard_exports.HasPropertyKey(context2, type.$ref) ? FromType26(context2, context2[type.$ref], value) : (() => {\n throw new RepairError(context2, type, value, \"Unable to de-reference target type\");\n })();\n }\n\n // node_modules/typebox/build/value/repair/from_template_literal.mjs\n function FromTemplateLiteral6(context2, type, value) {\n const decoded = TemplateLiteralDecode(type.pattern);\n return FromType26(context2, decoded, value);\n }\n\n // node_modules/typebox/build/value/repair/from_tuple.mjs\n function FromTuple11(context2, schema, value) {\n if (Check2(context2, schema, value))\n return value;\n if (!guard_exports.IsArray(value))\n return Create2(context2, schema);\n return schema.items.map((schema2, index3) => FromType26(context2, schema2, value[index3]));\n }\n\n // node_modules/typebox/build/value/shared/union_score_select.mjs\n function Deref(context2, type, value) {\n return IsRef2(type) ? guard_exports.HasPropertyKey(context2, type.$ref) ? Deref(context2, context2[type.$ref], value) : (() => {\n throw new Error(\"Unable to Deref target\");\n })() : type;\n }\n function ScoreVariant(context2, type, value) {\n if (!(IsObject3(type) && guard_exports.IsObject(value)))\n return 0;\n const keys = guard_exports.Keys(value);\n const entries = guard_exports.Entries(type.properties);\n return entries.reduce((result, [key, schema]) => {\n const literal = IsLiteral(schema) && guard_exports.IsEqual(schema.const, value[key]) ? 100 : 0;\n const checks = Check2(context2, schema, value[key]) ? 10 : 0;\n const exists = keys.includes(key) ? 1 : 0;\n return result + (literal + checks + exists);\n }, 0);\n }\n function UnionScoreSelect(context2, type, value) {\n const schemas = type.anyOf.map((schema) => Deref(context2, schema, value));\n let [select, best] = [schemas[0], 0];\n for (const schema of schemas) {\n const score = ScoreVariant(context2, schema, value);\n if (score > best) {\n select = schema;\n best = score;\n }\n }\n return select;\n }\n\n // node_modules/typebox/build/value/repair/from_union.mjs\n function RepairUnion(context2, type, value) {\n const union = Union(Flatten(type.anyOf));\n const schema = UnionScoreSelect(context2, union, value);\n return FromType26(context2, schema, value);\n }\n function FromUnion15(context2, type, value) {\n if (Check2(context2, type, value))\n return Clone2(value);\n if (IsDefault(type))\n return Create2(context2, type);\n return RepairUnion(context2, type, value);\n }\n\n // node_modules/typebox/build/value/repair/from_unknown.mjs\n function FromUnknown2(context2, type, value) {\n if (Check2(context2, type, value))\n return value;\n const converted = Convert(context2, type, value);\n if (Check2(context2, type, converted))\n return converted;\n return Create2(context2, type);\n }\n\n // node_modules/typebox/build/value/repair/from_type.mjs\n function AssertRepairableValue(context2, type, value) {\n const unsupported = globals_exports.IsDate(value) || globals_exports.IsMap(value) || globals_exports.IsSet(value) || globals_exports.IsTypeArray(value) || guard_exports.IsConstructor(value) || guard_exports.IsFunction(value);\n if (unsupported) {\n throw new RepairError(context2, type, value, \"Value is not repairable\");\n }\n }\n function AssertRepairableType(context2, type, value) {\n const unsupported = IsConstructor3(type) || IsFunction3(type) || IsNever(type);\n if (unsupported) {\n throw new RepairError(context2, type, value, \"Type is not repairable\");\n }\n }\n function CreateWhenUndefined(context2, type, value) {\n return guard_exports.IsUndefined(value) && !IsUndefined3(type) ? Create2(context2, type) : value;\n }\n function FinalizeRepair(context2, type, repaired) {\n return IsRefine2(type) ? Check2(context2, type, repaired) ? repaired : Create2(context2, type) : repaired;\n }\n function FromType26(context2, type, value) {\n AssertRepairableValue(context2, type, value);\n AssertRepairableType(context2, type, value);\n const candidate = CreateWhenUndefined(context2, type, value);\n const repaired = IsArray3(type) ? FromArray14(context2, type, candidate) : IsEnum2(type) ? FromEnum5(context2, type, candidate) : IsIntersect(type) ? FromIntersect12(context2, type, candidate) : IsObject3(type) ? FromObject18(context2, type, candidate) : IsRecord(type) ? FromRecord9(context2, type, candidate) : IsRef2(type) ? FromRef11(context2, type, candidate) : IsTemplateLiteral(type) ? FromTemplateLiteral6(context2, type, candidate) : IsTuple(type) ? FromTuple11(context2, type, candidate) : IsUnion(type) ? FromUnion15(context2, type, candidate) : FromUnknown2(context2, type, candidate);\n return FinalizeRepair(context2, type, repaired);\n }\n\n // node_modules/typebox/build/value/repair/repair.mjs\n function Repair(...args) {\n const [context2, type, value] = arguments_exports.Match(args, {\n 3: (context3, type2, value2) => [context3, type2, value2],\n 2: (type2, value2) => [{}, type2, value2]\n });\n const repaired = FromType26(context2, type, value);\n Assert(context2, type, repaired);\n return repaired;\n }\n\n // node_modules/typebox/build/value/value.mjs\n var value_exports = {};\n __export(value_exports, {\n Assert: () => Assert,\n Check: () => Check2,\n Clean: () => Clean,\n Clone: () => Clone2,\n Convert: () => Convert,\n Create: () => Create2,\n Decode: () => Decode10,\n Default: () => Default,\n Diff: () => Diff,\n Encode: () => Encode10,\n Equal: () => Equal,\n Errors: () => Errors2,\n HasCodec: () => HasCodec,\n Hash: () => Hash2,\n Parse: () => Parse,\n Patch: () => Patch,\n Pointer: () => pointer_exports,\n Repair: () => Repair\n });\n\n // node_modules/typebox/build/compile/validator.mjs\n var Validator = class {\n /** Constructs a Validator. */\n constructor(context2, type) {\n this.hasCodec = HasCodec(context2, type);\n this.buildResult = Build(context2, type);\n this.evaluateResult = this.buildResult.Evaluate();\n }\n // ----------------------------------------------------------------\n // IsAccelerated\n // ----------------------------------------------------------------\n /** Returns true if this Validator is using JIT acceleration. */\n IsAccelerated() {\n return this.evaluateResult.IsAccelerated();\n }\n // ----------------------------------------------------------------\n // Context & Type\n // ----------------------------------------------------------------\n /** Returns the Context for this validator. */\n Context() {\n return this.buildResult.Context();\n }\n /** Returns the underlying Type used to construct this Validator. */\n Type() {\n return this.buildResult.Schema();\n }\n // ----------------------------------------------------------------\n // Code\n // ----------------------------------------------------------------\n /** Returns the generated code for this validator. */\n Code() {\n return this.evaluateResult.Code();\n }\n // ----------------------------------------------------------------\n // Standard Validator\n // ----------------------------------------------------------------\n /** Performs a type-guard check on the provided value. */\n Check(value) {\n return this.evaluateResult.Check(value);\n }\n /** Validates a value and returns it. Will throw if invalid. */\n Parse(value) {\n const checked = this.Check(value);\n if (checked)\n return value;\n if (settings_exports.Get().correctiveParse)\n return Parser(this.Context(), this.Type(), value);\n throw new ParseError(value, this.Errors(value));\n }\n /** Returns an array of validation errors for the given value. */\n Errors(value) {\n if (this.IsAccelerated() && this.Check(value))\n return [];\n return Errors2(this.Context(), this.Type(), value);\n }\n // ----------------------------------------------------------------\n // Value.* Operations\n // ----------------------------------------------------------------\n /** Cleans a value using the Validator type. */\n Clean(value) {\n return Clean(this.Context(), this.Type(), value);\n }\n /** Converts a value using the Validator type. */\n Convert(value) {\n return Convert(this.Context(), this.Type(), value);\n }\n /** Creates a value using the Validator type. */\n Create() {\n return Create2(this.Context(), this.Type());\n }\n /** Creates defaults using the Validator type. */\n Default(value) {\n return Default(this.Context(), this.Type(), value);\n }\n /** Decodes a value */\n Decode(value) {\n const result = this.hasCodec ? Decode10(this.Context(), this.Type(), value) : this.Parse(value);\n return result;\n }\n /** Encodes a value */\n Encode(value) {\n const result = this.hasCodec ? Encode10(this.Context(), this.Type(), value) : this.Parse(value);\n return result;\n }\n };\n\n // node_modules/typebox/build/compile/compile.mjs\n function Compile(...args) {\n const [context2, type] = arguments_exports.Match(args, {\n 2: (context3, type2) => [context3, type2],\n 1: (type2) => [{}, type2]\n });\n return new Validator(context2, type);\n }\n\n // node_modules/@earendil-works/pi-ai/dist/utils/validation.js\n var validatorCache = /* @__PURE__ */ new WeakMap();\n var TYPEBOX_KIND = /* @__PURE__ */ Symbol.for(\"TypeBox.Kind\");\n function getSchemaTypes(schema) {\n if (typeof schema.type === \"string\") {\n return [schema.type];\n }\n if (Array.isArray(schema.type)) {\n return schema.type.filter((type) => typeof type === \"string\");\n }\n return [];\n }\n function matchesJsonType(value, type) {\n switch (type) {\n case \"number\":\n return typeof value === \"number\";\n case \"integer\":\n return typeof value === \"number\" && Number.isInteger(value);\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"string\":\n return typeof value === \"string\";\n case \"null\":\n return value === null;\n case \"array\":\n return Array.isArray(value);\n case \"object\":\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n default:\n return false;\n }\n }\n function getSubSchemaValidator(schema) {\n try {\n return getValidator(schema);\n } catch {\n return void 0;\n }\n }\n function coercePrimitiveByType(value, type) {\n switch (type) {\n case \"number\": {\n if (value === null) {\n return 0;\n }\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) {\n return parsed;\n }\n }\n if (typeof value === \"boolean\") {\n return value ? 1 : 0;\n }\n return value;\n }\n case \"integer\": {\n if (value === null) {\n return 0;\n }\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value);\n if (Number.isInteger(parsed)) {\n return parsed;\n }\n }\n if (typeof value === \"boolean\") {\n return value ? 1 : 0;\n }\n return value;\n }\n case \"boolean\": {\n if (value === null) {\n return false;\n }\n if (typeof value === \"string\") {\n if (value === \"true\") {\n return true;\n }\n if (value === \"false\") {\n return false;\n }\n }\n if (typeof value === \"number\") {\n if (value === 1) {\n return true;\n }\n if (value === 0) {\n return false;\n }\n }\n return value;\n }\n case \"string\": {\n if (value === null) {\n return \"\";\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n return value;\n }\n case \"null\": {\n if (value === \"\" || value === 0 || value === false) {\n return null;\n }\n return value;\n }\n default:\n return value;\n }\n }\n function applySchemaObjectCoercion(value, schema) {\n const properties = schema.properties;\n const definedKeys = new Set(properties ? Object.keys(properties) : []);\n if (properties) {\n for (const [key, propertySchema] of Object.entries(properties)) {\n if (!(key in value)) {\n continue;\n }\n value[key] = coerceWithJsonSchema(value[key], propertySchema);\n }\n }\n if (schema.additionalProperties && typeof schema.additionalProperties === \"object\") {\n for (const [key, propertyValue] of Object.entries(value)) {\n if (definedKeys.has(key)) {\n continue;\n }\n value[key] = coerceWithJsonSchema(propertyValue, schema.additionalProperties);\n }\n }\n }\n function applySchemaArrayCoercion(value, schema) {\n if (Array.isArray(schema.items)) {\n for (let index3 = 0; index3 < value.length; index3++) {\n const itemSchema = schema.items[index3];\n if (!itemSchema) {\n continue;\n }\n value[index3] = coerceWithJsonSchema(value[index3], itemSchema);\n }\n return;\n }\n if (schema.items && typeof schema.items === \"object\") {\n for (let index3 = 0; index3 < value.length; index3++) {\n value[index3] = coerceWithJsonSchema(value[index3], schema.items);\n }\n }\n }\n function coerceWithUnionSchema(value, schemas) {\n for (const schema of schemas) {\n const validator = getSubSchemaValidator(schema);\n if (validator?.Check(value)) {\n return value;\n }\n }\n for (const schema of schemas) {\n const candidate = structuredClone(value);\n const coerced = coerceWithJsonSchema(candidate, schema);\n const validator = getSubSchemaValidator(schema);\n if (validator?.Check(coerced)) {\n return coerced;\n }\n }\n return value;\n }\n function coerceWithJsonSchema(value, schema) {\n let nextValue = value;\n if (Array.isArray(schema.allOf)) {\n for (const nested of schema.allOf) {\n nextValue = coerceWithJsonSchema(nextValue, nested);\n }\n }\n if (Array.isArray(schema.anyOf)) {\n nextValue = coerceWithUnionSchema(nextValue, schema.anyOf);\n }\n if (Array.isArray(schema.oneOf)) {\n nextValue = coerceWithUnionSchema(nextValue, schema.oneOf);\n }\n const schemaTypes = getSchemaTypes(schema);\n const matchesUnionMember = schemaTypes.length > 1 && schemaTypes.some((schemaType) => matchesJsonType(nextValue, schemaType));\n if (schemaTypes.length > 0 && !matchesUnionMember) {\n for (const schemaType of schemaTypes) {\n const candidate = coercePrimitiveByType(nextValue, schemaType);\n if (candidate !== nextValue) {\n nextValue = candidate;\n break;\n }\n }\n }\n if (schemaTypes.includes(\"object\") && typeof nextValue === \"object\" && nextValue !== null && !Array.isArray(nextValue)) {\n applySchemaObjectCoercion(nextValue, schema);\n }\n if (schemaTypes.includes(\"array\") && Array.isArray(nextValue)) {\n applySchemaArrayCoercion(nextValue, schema);\n }\n return nextValue;\n }\n function normalizeOptionalNulls(value, schema) {\n if (Array.isArray(value)) {\n if (Array.isArray(schema.items)) {\n for (let index3 = 0; index3 < value.length; index3++) {\n const itemSchema = schema.items[index3];\n if (itemSchema)\n normalizeOptionalNulls(value[index3], itemSchema);\n }\n } else if (schema.items) {\n for (const item of value)\n normalizeOptionalNulls(item, schema.items);\n }\n return;\n }\n if (typeof value !== \"object\" || value === null || !schema.properties)\n return;\n const object = value;\n const required = new Set(schema.required ?? []);\n for (const [key, propertySchema] of Object.entries(schema.properties)) {\n if (!(key in object))\n continue;\n if (object[key] === null && !required.has(key) && typeof propertySchema.$ref !== \"string\" && getSubSchemaValidator(propertySchema)?.Check(null) === false) {\n delete object[key];\n } else {\n normalizeOptionalNulls(object[key], propertySchema);\n }\n }\n }\n function getValidator(schema) {\n const key = schema;\n const cached = validatorCache.get(key);\n if (cached) {\n return cached;\n }\n const validator = Compile(schema);\n validatorCache.set(key, validator);\n return validator;\n }\n function formatValidationPath(error) {\n if (error.keyword === \"required\") {\n const requiredProperties = error.params.requiredProperties;\n const requiredProperty = requiredProperties?.[0];\n if (requiredProperty) {\n const basePath = error.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\");\n return basePath ? `${basePath}.${requiredProperty}` : requiredProperty;\n }\n }\n const path = error.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\");\n return path || \"root\";\n }\n function validateToolArguments(tool, toolCall) {\n const args = structuredClone(toolCall.arguments);\n normalizeOptionalNulls(args, tool.parameters);\n value_exports.Convert(tool.parameters, args);\n const validator = getValidator(tool.parameters);\n if (!Object.getOwnPropertySymbols(tool.parameters).includes(TYPEBOX_KIND)) {\n const coerced = coerceWithJsonSchema(args, tool.parameters);\n if (coerced !== args) {\n if (typeof args === \"object\" && args !== null && typeof coerced === \"object\" && coerced !== null) {\n for (const key of Object.keys(args)) {\n delete args[key];\n }\n Object.assign(args, coerced);\n } else {\n return validator.Check(coerced) ? coerced : args;\n }\n }\n }\n if (validator.Check(args)) {\n return args;\n }\n const errors = validator.Errors(args).map((error) => ` - ${formatValidationPath(error)}: ${error.message}`).join(\"\\n\") || \"Unknown validation error\";\n const errorMessage = `Validation failed for tool \"${toolCall.name}\":\n${errors}\n\nReceived arguments:\n${JSON.stringify(toolCall.arguments, null, 2)}`;\n throw new Error(errorMessage);\n }\n\n // node_modules/@earendil-works/pi-durable/dist/truncate.js\n var DEFAULT_MAX_LINES = 2e3;\n var DEFAULT_MAX_BYTES = 50 * 1024;\n var runtimeBuffer = globalThis.Buffer;\n var nonAsciiPattern = /[^\\x00-\\x7f]/;\n function utf8ByteLength(content) {\n if (runtimeBuffer)\n return runtimeBuffer.byteLength(content, \"utf8\");\n const firstNonAscii = content.search(nonAsciiPattern);\n if (firstNonAscii === -1)\n return content.length;\n let bytes = firstNonAscii;\n for (let i = firstNonAscii; i < content.length; i++) {\n const code = content.charCodeAt(i);\n if (code <= 127) {\n bytes += 1;\n } else if (code <= 2047) {\n bytes += 2;\n } else if (code >= 55296 && code <= 56319 && i + 1 < content.length) {\n const next = content.charCodeAt(i + 1);\n if (next >= 56320 && next <= 57343) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n } else {\n bytes += 3;\n }\n }\n return bytes;\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/output.js\n var NEWLINE = 10;\n var INVALID_OUTPUT = /[\\x00-\\x08\\x0b-\\x1f\\ufff9-\\ufffb]/g;\n var encoder2 = new TextEncoder();\n var decoder = new TextDecoder(\"utf-8\", { ignoreBOM: true });\n function sanitizeOutput(text) {\n return text.replace(INVALID_OUTPUT, \"\");\n }\n function boundOutput(text, limits) {\n const bytes = encoder2.encode(text);\n const [from, to] = limits.retain === \"head\" ? headRange(bytes, limits) : tailRange(bytes, limits);\n const kept = bytes.subarray(from, to);\n return {\n text: kept.length === bytes.length ? text : decoder.decode(kept),\n bytes: kept.length,\n droppedBytes: bytes.length - kept.length,\n droppedLines: lineCount(bytes) - lineCount(kept)\n };\n }\n function headRange(bytes, limits) {\n if (limits.maxLines === 0 || limits.maxBytes === 0)\n return [0, 0];\n let end = bytes.length;\n let lines2 = 0;\n for (let index3 = bytes.indexOf(NEWLINE); index3 !== -1; index3 = bytes.indexOf(NEWLINE, index3 + 1)) {\n if (++lines2 === limits.maxLines) {\n end = index3 + 1;\n break;\n }\n }\n if (end > limits.maxBytes) {\n const newline = bytes.lastIndexOf(NEWLINE, limits.maxBytes - 1);\n end = newline === -1 ? characterEnd(bytes, limits.maxBytes) : newline + 1;\n }\n return [0, end];\n }\n function tailRange(bytes, limits) {\n if (limits.maxLines === 0 || limits.maxBytes === 0)\n return [bytes.length, bytes.length];\n const last = bytes[bytes.length - 1] === NEWLINE ? bytes.length - 2 : bytes.length - 1;\n let start = 0;\n let lines2 = 1;\n for (let index3 = last < 0 ? -1 : bytes.lastIndexOf(NEWLINE, last); index3 !== -1; ) {\n if (lines2 === limits.maxLines) {\n start = index3 + 1;\n break;\n }\n lines2++;\n index3 = index3 === 0 ? -1 : bytes.lastIndexOf(NEWLINE, index3 - 1);\n }\n if (bytes.length - start > limits.maxBytes) {\n const from = bytes.length - limits.maxBytes;\n const newline = bytes.indexOf(NEWLINE, from - 1);\n start = newline !== -1 && newline + 1 < bytes.length ? newline + 1 : characterStart(bytes, from);\n }\n return [start, bytes.length];\n }\n function characterEnd(bytes, index3) {\n let end = index3;\n while (end > 0 && ((bytes[end] ?? 0) & 192) === 128)\n end--;\n return end;\n }\n function characterStart(bytes, index3) {\n let start = index3;\n while (start < bytes.length && ((bytes[start] ?? 0) & 192) === 128)\n start++;\n return start;\n }\n function lineCount(bytes) {\n if (bytes.length === 0)\n return 0;\n let newlines = 0;\n for (let index3 = bytes.indexOf(NEWLINE); index3 !== -1; index3 = bytes.indexOf(NEWLINE, index3 + 1))\n newlines++;\n return newlines + (bytes[bytes.length - 1] === NEWLINE ? 0 : 1);\n }\n var OutputBuffer = class {\n #limits;\n /**\n * Decoder of byte chunks. A string chunk or a skip ends an incomplete character of earlier bytes (it becomes U+FFFD);\n * the next byte chunk then starts a new character. As in `StreamDecoder`, only a byte-order mark at the very start of\n * the output is dropped, never a U+FEFF later in it.\n */\n #decoder = new TextDecoder(\"utf-8\", { ignoreBOM: true });\n #started = false;\n /** Stored chunks: for head the start of the stream, for tail a suffix that still contains the next window. */\n #chunks = [];\n #storedBytes = 0;\n #storedNewlines = 0;\n #full = false;\n #totalBytes = 0;\n #totalNewlines = 0;\n #endsWithNewline = true;\n constructor(limits) {\n this.#limits = limits;\n }\n /** Bytes currently held; bounded by the limits plus one chunk. */\n get storedBytes() {\n return this.#storedBytes;\n }\n /**\n * Accept a chunk; returns whether anything was accepted. `skipped` is output omitted right before the chunk, which\n * must be more than the tail window by at least one byte or line (`ShellOutputInfo.skipped`); only tail retention\n * accepts it.\n */\n push(chunk, skipped) {\n const pending = typeof chunk === \"string\" || skipped !== void 0 ? this.#decoder.decode() : \"\";\n let text = typeof chunk === \"string\" ? chunk : this.#decoder.decode(chunk, { stream: true });\n const first = !this.#started && pending === \"\" && skipped === void 0;\n if (pending !== \"\" || text !== \"\" || skipped !== void 0)\n this.#started = true;\n if (first && typeof chunk !== \"string\" && text.startsWith(\"\\uFEFF\"))\n text = text.slice(1);\n if (skipped === void 0)\n return this.#accept(pending + text);\n if (this.#limits.retain !== \"tail\")\n throw new Error(\"Skipped output requires tail retention\");\n this.#accept(pending);\n this.#skip(skipped);\n this.#accept(text);\n return true;\n }\n /** Count omitted output; nothing stored before it can be in the window once the text after it arrives. */\n #skip(skipped) {\n if (skipped.bytes === 0)\n return;\n this.#totalBytes += skipped.bytes;\n this.#totalNewlines += skipped.newlines;\n this.#endsWithNewline = skipped.endsWithNewline;\n this.#chunks = [];\n this.#storedBytes = 0;\n this.#storedNewlines = 0;\n }\n /** Flush an incomplete trailing character as a replacement character; call when the stream ends. */\n end() {\n this.#accept(this.#decoder.decode());\n }\n #accept(text) {\n if (text.length === 0)\n return false;\n const bytes = utf8ByteLength(text);\n const newlines = countNewlines(text);\n this.#totalBytes += bytes;\n this.#totalNewlines += newlines;\n this.#endsWithNewline = text.endsWith(\"\\n\");\n if (this.#full)\n return true;\n this.#chunks.push({ text, bytes, newlines });\n this.#storedBytes += bytes;\n this.#storedNewlines += newlines;\n if (this.#limits.retain === \"head\") {\n this.#full = this.#storedBytes > this.#limits.maxBytes || this.#storedNewlines >= this.#limits.maxLines;\n return true;\n }\n while (this.#chunks.length > 1) {\n const first = this.#chunks[0];\n const bytesAfter = this.#storedBytes - first.bytes;\n const newlinesAfter = this.#storedNewlines - first.newlines;\n if (bytesAfter <= this.#limits.maxBytes + 1 && newlinesAfter <= this.#limits.maxLines + 1)\n break;\n this.#chunks.shift();\n this.#storedBytes = bytesAfter;\n this.#storedNewlines = newlinesAfter;\n }\n return true;\n }\n /** Retained, sanitized output and what the limits dropped from the whole stream. */\n snapshot() {\n const stored = this.#chunks.length === 1 ? this.#chunks[0].text : this.#chunks.map((chunk) => chunk.text).join(\"\");\n const kept = boundOutput(stored, this.#limits);\n const storedLines = lines(this.#storedNewlines, stored === \"\" || stored.endsWith(\"\\n\"));\n const keptLines = storedLines - kept.droppedLines;\n if (this.#limits.retain === \"tail\" || this.#chunks.length > 1) {\n const text = this.#limits.retain === \"tail\" ? tailMargin(stored, this.#limits) : stored;\n const bytes = this.#limits.retain === \"tail\" ? utf8ByteLength(text) : this.#storedBytes;\n this.#chunks = text === \"\" ? [] : [{ text, bytes, newlines: countNewlines(text) }];\n this.#storedBytes = bytes;\n this.#storedNewlines = this.#chunks[0]?.newlines ?? 0;\n }\n return {\n text: sanitizeOutput(kept.text),\n droppedBytes: this.#totalBytes - kept.bytes,\n droppedLines: lines(this.#totalNewlines, this.#endsWithNewline) - keptLines\n };\n }\n };\n function tailMargin(text, limits) {\n const bytes = encoder2.encode(text);\n const byteStart = bytes.length > limits.maxBytes ? characterEnd(bytes, bytes.length - limits.maxBytes - 1) : 0;\n let lineStart = 0;\n let newlines = 0;\n for (let index3 = bytes.lastIndexOf(NEWLINE); index3 !== -1; index3 = bytes.lastIndexOf(NEWLINE, index3 - 1)) {\n if (++newlines > limits.maxLines) {\n lineStart = index3;\n break;\n }\n if (index3 === 0)\n break;\n }\n const start = Math.max(byteStart, lineStart);\n return start === 0 ? text : decoder.decode(bytes.subarray(start));\n }\n function lines(newlines, terminated) {\n return newlines + (terminated ? 0 : 1);\n }\n function countNewlines(text) {\n let count = 0;\n for (let index3 = text.indexOf(\"\\n\"); index3 !== -1; index3 = text.indexOf(\"\\n\", index3 + 1))\n count++;\n return count;\n }\n var PROGRESS_BYTES_PER_SECOND = 100 * 1024;\n var Progress = class {\n #write;\n #onError;\n #minIntervalMs;\n #waiters = [];\n #timer;\n #inFlight;\n #nextAt = 0;\n #dirty = false;\n #stopped = false;\n constructor(write, onError, minIntervalMs) {\n this.#write = write;\n this.#onError = onError;\n this.#minIntervalMs = minIntervalMs;\n }\n /** Schedule a commit. */\n mark() {\n this.#dirty = true;\n this.#schedule();\n }\n /** Schedule a commit; the promise settles with the commit that includes this change. */\n markAndWait() {\n const waiter = Promise.withResolvers();\n this.#waiters.push(waiter);\n this.mark();\n return waiter.promise;\n }\n /** Stop committing and wait for the commit in flight; returns the waiters the final commit must settle. */\n async stop() {\n this.#stopped = true;\n clearTimeout(this.#timer);\n this.#timer = void 0;\n await this.#inFlight;\n return this.#waiters.splice(0);\n }\n #schedule() {\n if (this.#stopped || this.#timer !== void 0 || this.#inFlight !== void 0)\n return;\n const wait = this.#nextAt - Date.now();\n if (wait <= 0)\n this.#flush();\n else\n this.#timer = setTimeout(() => {\n this.#timer = void 0;\n this.#flush();\n }, wait);\n }\n #flush() {\n if (this.#stopped || !this.#dirty)\n return;\n this.#dirty = false;\n const waiters = this.#waiters.splice(0);\n const started = Date.now();\n this.#inFlight = this.#write().then((bytes) => {\n this.#nextAt = started + Math.max(this.#minIntervalMs, bytes * 1e3 / PROGRESS_BYTES_PER_SECOND);\n for (const waiter of waiters)\n waiter.resolve();\n }, (error) => {\n this.#nextAt = started + this.#minIntervalMs;\n for (const waiter of waiters)\n waiter.reject(error);\n this.#onError(error);\n }).finally(() => {\n this.#inFlight = void 0;\n if (this.#dirty)\n this.#schedule();\n });\n }\n };\n\n // node_modules/@earendil-works/pi-durable/dist/harness/usage.js\n var UsageDoc = defineDoc({\n kind: \"pi.usage\",\n version: 1,\n scope: \"conversation\",\n history: \"latest\",\n fork: \"initial\",\n initial: () => ({ models: {}, tools: {} }),\n checkpointWhen: () => true\n });\n async function recordUsage(tx, conversationId, bucket, key, usage2) {\n const totals = (await tx.doc(UsageDoc, conversationId))[bucket];\n const total = Object.hasOwn(totals, key) ? totals[key] : void 0;\n if (total === void 0)\n totals[key] = copyJson(usage2, { omitUndefinedProperties: true });\n else\n addUsage(total, usage2);\n }\n function addUsage(total, usage2) {\n total.input += usage2.input;\n total.output += usage2.output;\n total.cacheRead += usage2.cacheRead;\n total.cacheWrite += usage2.cacheWrite;\n total.totalTokens += usage2.totalTokens;\n if (usage2.cacheWrite1h !== void 0)\n total.cacheWrite1h = (total.cacheWrite1h ?? 0) + usage2.cacheWrite1h;\n if (usage2.reasoning !== void 0)\n total.reasoning = (total.reasoning ?? 0) + usage2.reasoning;\n total.cost.input += usage2.cost.input;\n total.cost.output += usage2.cost.output;\n total.cost.cacheRead += usage2.cost.cacheRead;\n total.cost.cacheWrite += usage2.cost.cacheWrite;\n total.cost.total += usage2.cost.total;\n }\n function addUsageState(sum, state2) {\n for (const bucket of [\"models\", \"tools\"]) {\n for (const [key, usage2] of Object.entries(state2[bucket])) {\n const total = Object.hasOwn(sum[bucket], key) ? sum[bucket][key] : void 0;\n if (total !== void 0)\n addUsage(total, usage2);\n else\n Object.defineProperty(sum[bucket], key, {\n value: structuredClone(usage2),\n enumerable: true,\n writable: true\n });\n }\n }\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/tool.js\n var ToolTask = defineTask({\n name: \"pi.tool\",\n version: 1,\n initial: () => ({ phase: \"call\" }),\n phases: {\n call: async (task, runtime, context2) => {\n const call = await readCall(runtime, task.input, context2);\n const tool = (await runtime.agent(context2)).tools.find((each) => each.name === call.name);\n if (tool === void 0) {\n const error = harnessError(\"tool_unavailable\", `Tool ${call.name} is not available`);\n return settle2(runtime, call, COMPLETED, () => error, context2);\n }\n const prepared = prepare(tool, call.arguments);\n const checked = \"error\" in prepared ? prepared : validate(tool, call, prepared.args);\n if (\"error\" in checked)\n return settle2(runtime, call, COMPLETED, () => invalid(checked.error), context2);\n let args = checked.args;\n let block;\n await runtime.hooks.each(\"beforeTool\", async (hook2) => {\n if (block !== void 0)\n return;\n try {\n const decision = await hook2({ ...call, arguments: args }, runtime, context2);\n if (decision?.block !== void 0)\n block = decision.block;\n else if (decision?.arguments !== void 0)\n args = decision.arguments;\n } catch (error) {\n if (runtime.signal.aborted)\n throw error;\n block = errorText(error);\n }\n });\n if (block !== void 0) {\n const blocked = harnessError(\"blocked\", `Tool call blocked: ${block}`);\n return settle2(runtime, call, COMPLETED, () => blocked, context2);\n }\n const validated = validate(tool, call, args);\n if (\"error\" in validated)\n return settle2(runtime, call, COMPLETED, () => invalid(validated.error), context2);\n const final = validated.args;\n await runtime.commit(async (tx) => {\n const slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n if (slot !== void 0)\n slot.status = \"running\";\n const intent = { phase: \"execute\", arguments: final, replay: tool.replay ?? \"unsafe\" };\n return { status: \"running\", checkpoint: intent };\n }, context2);\n await run(runtime, call, tool, final, context2);\n },\n /** Recovery after intent: rerun only when the stored and the current policy both say `safe`. */\n execute: async (task, runtime, context2) => {\n const { arguments: args, replay } = task.state.checkpoint;\n const call = await readCall(runtime, task.input, context2);\n const tool = (await runtime.agent(context2)).tools.find((each) => each.name === call.name);\n if (replay === \"safe\" && tool?.replay === \"safe\") {\n await runtime.commit(async (tx) => {\n const slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n if (slot !== void 0)\n clearProgress(slot);\n return void 0;\n }, context2);\n return run(runtime, call, tool, args, context2);\n }\n const message = `Tool ${call.name} was interrupted and may have partially run`;\n const ending = { status: \"failed\", message };\n await settle2(runtime, call, ending, (slot) => fromSlot(slot, \"interrupted\", message), context2);\n }\n },\n abort: async (task, runtime, context2) => {\n const call = await readCall(runtime, task.input, context2);\n const message = `Tool ${call.name} was aborted`;\n await settle2(runtime, call, { status: \"aborted\" }, (slot) => fromSlot(slot, \"aborted\", message), context2);\n }\n });\n async function readCall(runtime, input, context2) {\n const entry = await runtime.entry(AssistantEntry, input.assistant, context2);\n const message = entry?.model?.[0];\n const call = message?.role === \"assistant\" ? message.content.find((content) => content.type === \"toolCall\" && content.id === input.callId) : void 0;\n if (call === void 0)\n throw new Error(`Entry ${input.assistant} has no tool call ${input.callId}`);\n return call;\n }\n function prepare(tool, args) {\n if (tool.prepareArguments === void 0)\n return { args };\n try {\n return { args: tool.prepareArguments(args) };\n } catch (error) {\n return { error: errorText(error) };\n }\n }\n function validate(tool, call, args) {\n try {\n return { args: validateToolArguments(tool, { ...call, arguments: args }) };\n } catch (error) {\n return { error: errorText(error) };\n }\n }\n function invalid(message) {\n return harnessError(\"invalid_arguments\", message);\n }\n async function run(runtime, call, tool, args, context2) {\n const limits = {\n maxBytes: tool.outputLimits?.maxBytes ?? DEFAULT_MAX_BYTES,\n maxLines: tool.outputLimits?.maxLines ?? DEFAULT_MAX_LINES,\n retain: tool.outputLimits?.retain ?? \"head\"\n };\n const reported = { output: new OutputBuffer(limits), limits, diagnostics: [], details: void 0 };\n const progress = publishProgress(runtime, reported, context2);\n let ended = false;\n const assertLive = () => {\n if (ended)\n throw new Error(`Tool call ${call.id} has settled`);\n };\n const api2 = {\n taskId: runtime.taskId,\n conversationId: runtime.conversationId,\n callId: call.id,\n registry: runtime.registry,\n agent: runtime.agent,\n models: runtime.models,\n output: (chunk, skipped) => {\n assertLive();\n if (reported.output.push(chunk, skipped))\n progress.mark();\n },\n outputWindow: limits.retain === \"tail\" ? {\n maxBytes: limits.maxBytes,\n maxLines: limits.maxLines,\n minIntervalMs: runtime.settings.progress.outputIntervalMs,\n bytesPerSecond: PROGRESS_BYTES_PER_SECOND\n } : void 0,\n diagnostic: (diagnostic) => {\n assertLive();\n reported.diagnostics.push(copyJson(diagnostic, { omitUndefinedProperties: true }));\n progress.mark();\n },\n details: async (value, detailsContext) => {\n assertLive();\n detailsContext.abortSignal?.throwIfAborted();\n reported.details = copyJson(value, { omitUndefinedProperties: true });\n const committed = progress.markAndWait();\n committed.catch(() => {\n });\n return awaitWithContext(committed, detailsContext);\n },\n commit: async (change, commitContext) => {\n let result2;\n await runtime.commit(async (tx) => {\n result2 = await change(tx);\n return void 0;\n }, commitContext);\n return result2;\n },\n memo: runtime.memo,\n createTask: async (task, input, options, taskContext) => {\n let id;\n await runtime.commit(async (tx) => {\n id = await tx.createTask(task, input, options);\n return void 0;\n }, taskContext);\n return id;\n },\n getTask: runtime.getTask,\n waitForTask: runtime.waitForTask,\n conversation: runtime.conversation,\n snapshot: runtime.snapshot,\n snapshotAsOf: runtime.snapshotAsOf,\n watchDoc: runtime.watchDoc\n };\n let result;\n let ending = COMPLETED;\n let durationMs;\n try {\n const env = await runtime.env(context2);\n const startedAt = performance.now();\n try {\n result = await tool.execute(args, { ...api2, env }, context2);\n } finally {\n durationMs = Math.round(performance.now() - startedAt);\n }\n } catch (error) {\n if (runtime.signal.aborted) {\n ended = true;\n for (const waiter of await progress.stop())\n waiter.reject(error);\n throw error;\n }\n result = { isError: true, diagnostics: [toolDiagnostic(\"tool_error\", errorText(error))] };\n ending = { status: \"failed\", message: `Tool ${call.name} threw` };\n }\n ended = true;\n reported.output.end();\n const pending = await progress.stop();\n try {\n const settled = await finalResult(runtime, call, result, reported, context2);\n await settle2(runtime, call, ending, () => settled, context2, durationMs);\n } catch (error) {\n for (const waiter of pending)\n waiter.reject(error);\n throw error;\n }\n for (const waiter of pending)\n waiter.resolve();\n }\n function publishProgress(runtime, reported, context2) {\n let written = { text: \"\", details: void 0, diagnostics: 0 };\n return new Progress(async () => {\n const snapshot = reported.output.snapshot();\n const current = { text: snapshot.text, details: reported.details, diagnostics: reported.diagnostics.length };\n const added = reported.diagnostics.slice(written.diagnostics, current.diagnostics);\n const detailsChanged = current.details !== written.details;\n let bytes = 0;\n if (snapshot.text !== written.text) {\n const shared = snapshot.text.startsWith(written.text) ? written.text.length : overlap(written.text, snapshot.text, 65536);\n bytes += utf8ByteLength(snapshot.text.slice(shared));\n }\n if (detailsChanged)\n bytes += utf8ByteLength(JSON.stringify(current.details ?? null));\n if (added.length > 0)\n bytes += utf8ByteLength(JSON.stringify(added));\n await runtime.commit(async (tx) => {\n const slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n if (slot === void 0)\n return void 0;\n if ((slot.output ?? \"\") !== snapshot.text)\n slot.output = snapshot.text;\n if (snapshot.droppedBytes > 0)\n slot.droppedBytes = snapshot.droppedBytes;\n if (snapshot.droppedLines > 0)\n slot.droppedLines = snapshot.droppedLines;\n if (detailsChanged && current.details !== void 0) {\n assignJson(slot, \"details\", current.details);\n }\n if (added.length > 0) {\n if (slot.diagnostics === void 0)\n slot.diagnostics = [];\n for (const diagnostic of added)\n slot.diagnostics.push(diagnostic);\n }\n return void 0;\n }, context2);\n written = current;\n return bytes;\n }, (error) => {\n if (!runtime.signal.aborted)\n runtime.report(error);\n }, runtime.settings.progress.outputIntervalMs);\n }\n async function finalResult(runtime, call, result, reported, context2) {\n const harness2 = [];\n const retained = result.content === void 0 ? reported.output.snapshot() : void 0;\n const content = retained === void 0 ? result.content : retained.text === \"\" ? [] : [{ type: \"text\", text: retained.text }];\n let final = {\n ...result,\n content,\n details: result.details === void 0 ? reported.details : result.details,\n diagnostics: [...reported.diagnostics, ...result.diagnostics ?? []]\n };\n await runtime.hooks.each(\"afterTool\", async (hook2) => {\n final = await hook2(call, final, runtime, context2) ?? final;\n });\n if (retained !== void 0 && retained.droppedBytes > 0 && final.content === content) {\n harness2.push(truncated(retained, reported.limits.retain));\n }\n const bounded = boundContent(final.content ?? [], reported.limits);\n if (bounded.droppedBytes > 0)\n harness2.push(truncated(bounded, reported.limits.retain));\n return { ...final, content: bounded.content, diagnostics: [...final.diagnostics ?? [], ...harness2] };\n }\n async function settle2(runtime, call, ending, build, context2, durationMs) {\n await runtime.commit(async (tx) => {\n const slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n const result = build(slot);\n const entry = await appendToolResult(tx, runtime.conversationId, call, result, runtime.now(), durationMs);\n if (slot !== void 0)\n finishSlot(slot, entry.id);\n const entryId = entry.id;\n if (ending.status === \"aborted\")\n return { status: \"terminal\", outcome: { status: \"aborted\", result: { entryId } } };\n if (ending.status === \"failed\") {\n const error = { message: ending.message };\n return { status: \"terminal\", outcome: { status: \"failed\", error, result: { entryId } } };\n }\n const control = result.control === void 0 ? {} : { control: copyJson(result.control, { omitUndefinedProperties: true }) };\n return { status: \"terminal\", outcome: { status: \"completed\", result: { entryId, ...control } } };\n }, context2);\n }\n var COMPLETED = { status: \"completed\" };\n function fromSlot(slot, code, message) {\n const diagnostics = [...slot?.diagnostics ?? []];\n const droppedBytes = slot?.droppedBytes ?? 0;\n if (droppedBytes > 0)\n diagnostics.push(truncated({ droppedBytes, droppedLines: slot?.droppedLines ?? 0 }));\n diagnostics.push(toolDiagnostic(code, message));\n return {\n content: slot?.output === void 0 || slot.output === \"\" ? [] : [{ type: \"text\", text: slot.output }],\n isError: true,\n ...slot?.details === void 0 ? {} : { details: slot.details },\n diagnostics\n };\n }\n function harnessError(code, message) {\n return { content: [], isError: true, diagnostics: [toolDiagnostic(code, message)] };\n }\n function toolDiagnostic(code, message) {\n return { severity: \"error\", code, message };\n }\n function truncated(dropped, retain) {\n const kept = retain === void 0 ? \"\" : ` to its ${retain === \"head\" ? \"beginning\" : \"end\"}`;\n return {\n severity: \"warn\",\n code: \"truncated\",\n message: `Output truncated${kept}: ${dropped.droppedLines} lines, ${dropped.droppedBytes} bytes dropped`\n };\n }\n async function appendToolResult(tx, conversationId, call, result, timestamp, durationMs) {\n const diagnostics = [...result.diagnostics ?? []];\n const content = [...result.content ?? []];\n if (diagnostics.length > 0)\n content.push({ type: \"text\", text: renderDiagnostics(diagnostics) });\n const message = {\n role: \"toolResult\",\n toolCallId: call.id,\n toolName: call.name,\n content,\n ...result.details === void 0 ? {} : { details: result.details },\n ...result.usage === void 0 ? {} : { usage: result.usage },\n isError: result.isError ?? false,\n ...durationMs === void 0 ? {} : { durationMs },\n timestamp\n };\n if (result.usage !== void 0)\n await recordUsage(tx, conversationId, \"tools\", call.name, result.usage);\n return tx.appendEntry(ToolResultEntry, conversationId, { model: [message], data: { diagnostics } });\n }\n function renderDiagnostics(diagnostics) {\n return `<harness>\n${diagnostics.map((diagnostic) => `[${diagnostic.severity}] ${diagnostic.message}`).join(\"\\n\")}\n</harness>`;\n }\n function boundContent(content, limits) {\n const texts = content.filter((item) => item.type === \"text\");\n const bounded = boundOutput(texts.map((item) => item.text).join(\"\"), limits);\n if (bounded.droppedBytes === 0)\n return { content, droppedBytes: 0, droppedLines: 0 };\n const keep = limits.retain === \"head\" ? texts[0] : texts.at(-1);\n const result = [];\n for (const item of content) {\n if (item.type !== \"text\")\n result.push(item);\n else if (item === keep)\n result.push({ ...item, text: bounded.text });\n }\n return { content: result, droppedBytes: bounded.droppedBytes, droppedLines: bounded.droppedLines };\n }\n function errorText(error) {\n return error instanceof Error ? error.message : String(error);\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/generation.js\n var DEFAULT_POLL_AFTER_MS = 5e3;\n var GenerationTask = defineTask({\n name: \"pi.generation\",\n version: 1,\n initial: () => ({ phase: \"prepare\", attempt: 1 }),\n phases: {\n /**\n * Render the system prompt and tool loadout and append the positional `pi.system` entries they need, then move to\n * `request`. The agent and settings resolved here are fixed for this request. Only the Harness writes to a busy\n * conversation, so the transcript read here is still the tail at the commit.\n */\n prepare: async (task, runtime, context2) => {\n const { conversationId } = runtime;\n const agent = await runtime.agent(context2);\n const settings2 = runtime.settings;\n const { model, thinkingLevel } = agent;\n const resolved = model === void 0 ? void 0 : runtime.models.getModel(model.provider, model.modelId);\n if (model === void 0 || resolved === void 0)\n return failNoModel(runtime, model, context2);\n const { attempt, compacted, overflow } = task.state.checkpoint;\n if (compacted !== void 0 && overflow !== void 0) {\n const [outcome] = await runtime.outcomes([compacted], context2);\n if (outcome?.status !== \"completed\" || outcome.result.entryId === void 0) {\n return failModelError(runtime, overflow, context2);\n }\n }\n const view = await runtime.context(conversationId, context2);\n const shown = replaySections(view.messages);\n const report = (error) => runtime.report(error);\n let env;\n try {\n env = await runtime.env(context2);\n } catch (error) {\n if (context2.abortSignal?.aborted)\n throw error;\n report(error);\n }\n const input = { conversationId, agent, env, shown: Object.fromEntries(shown), read: runtime };\n const desired = await renderSections(agent.sections, input, shown, report, context2);\n const entries = planSystemEntries(view, desired, agent.tools, runtime.now());\n const threshold = compacted === void 0 ? thresholdCompaction(view, entries, resolved.contextWindow, settings2.compaction) : void 0;\n if (threshold === \"blocking\") {\n await runtime.commit(async (tx) => {\n const child = await createCompaction(tx, conversationId, { reason: \"threshold\" }, runtime.taskId);\n const checkpoint = { phase: \"prepare\", attempt, compacted: child };\n return { status: \"waiting\", checkpoint, on: [child], policy: \"allSettled\" };\n }, context2);\n return;\n }\n await runtime.commit(async (tx) => {\n let cutoff = (await tx.scanEntries({ conversationId }, 1)).items[0]?.id;\n for (const entry of entries)\n cutoff = (await tx.appendEntry(SystemEntry, conversationId, entry)).id;\n if (cutoff === void 0)\n throw new Error(`Conversation ${conversationId} has no entries to send`);\n if (threshold === \"background\" && (await tx.doc(LiveDoc, conversationId)).compactions === void 0) {\n await createCompaction(tx, conversationId, { reason: \"threshold\" });\n }\n const request = {\n attempt,\n ...compacted === void 0 ? {} : { compacted },\n model,\n thinkingLevel,\n streamOptions: settings2.stream,\n cutoff\n };\n return { status: \"running\", checkpoint: { phase: \"request\", ...request } };\n }, context2);\n },\n request: async (task, runtime, context2) => {\n const { attempt, compacted, model: ref, thinkingLevel, streamOptions, cutoff } = task.state.checkpoint;\n const conversationId = runtime.conversationId;\n await runtime.commit(async (tx) => {\n const live = await tx.doc(LiveDoc, conversationId);\n await convertPartial(tx, live, conversationId);\n live.generation = { attempt };\n return void 0;\n }, context2);\n const model = runtime.models.getModel(ref.provider, ref.modelId);\n if (model === void 0)\n return failNoModel(runtime, ref, context2);\n const view = await runtime.context(conversationId, context2, { at: cutoff });\n let messages = view.messages;\n await runtime.hooks.each(\"beforeRequest\", async (hook2) => {\n const replaced = await hook2({ messages }, runtime, context2);\n if (replaced !== void 0)\n messages = replaced.messages;\n });\n const options = {\n ...streamOptions,\n signal: runtime.signal,\n sessionId: await ensureProviderSessionId(runtime, context2),\n ...thinkingLevel === \"off\" ? {} : { reasoning: thinkingLevel }\n };\n const message = await streamResponse(runtime, model, messages, options, attempt, context2);\n const request = { attempt, compacted, model: ref, cutoff, messages: view.messages };\n await classify(runtime, request, message, context2);\n },\n retry: async (task, runtime, context2) => {\n const { attempt, compacted, until } = task.state.checkpoint;\n await runtime.sleep(until, context2);\n await runtime.commit(async (tx) => {\n (await tx.doc(LiveDoc, runtime.conversationId)).generation = { attempt: attempt + 1 };\n const checkpoint = {\n phase: \"prepare\",\n attempt: attempt + 1,\n ...compacted === void 0 ? {} : { compacted }\n };\n return { status: \"running\", checkpoint };\n }, context2);\n },\n poll: async (task, runtime, context2) => {\n const { attempt, compacted, model: ref, cutoff, handle, pollAt } = task.state.checkpoint;\n const model = runtime.models.getModel(ref.provider, ref.modelId);\n if (model === void 0)\n return failNoModel(runtime, ref, context2);\n await runtime.sleep(pollAt, context2);\n const message = await runtime.models.fetchDeferred(model, handle, { signal: runtime.signal });\n const request = { attempt, compacted, model: ref, cutoff, pollAt };\n await classify(runtime, request, message, context2);\n },\n tools: async (task, runtime, context2) => {\n const { assistant, tools, pending } = task.state.checkpoint;\n const [next, ...rest] = pending;\n if (next === void 0)\n return finishToolRound(runtime, assistant, tools, context2);\n await runtime.commit(async (tx) => {\n const live = await tx.doc(LiveDoc, runtime.conversationId);\n const taskId = await createToolTask(tx, runtime, assistant, next);\n const slot = live.tools?.find((slot2) => slot2.callId === next && slot2.taskId === void 0);\n if (slot !== void 0)\n slot.taskId = taskId;\n const checkpoint = {\n phase: \"tools\",\n assistant,\n tools: [...tools, taskId],\n pending: rest\n };\n return { status: \"waiting\", checkpoint, on: [taskId], policy: \"allSettled\" };\n }, context2);\n }\n },\n abort: async (task, runtime, context2) => {\n const checkpoint = task.state.checkpoint;\n if (checkpoint.phase === \"poll\") {\n const model = runtime.models.getModel(checkpoint.model.provider, checkpoint.model.modelId);\n if (model !== void 0) {\n try {\n await runtime.models.cancelDeferred(model, checkpoint.handle, { signal: runtime.signal });\n } catch (error) {\n runtime.report(error);\n }\n }\n }\n const conversationId = runtime.conversationId;\n const unstarted = checkpoint.phase === \"tools\" ? await readCalls(runtime, checkpoint.assistant, checkpoint.pending, context2) : [];\n await runtime.commit(async (tx) => {\n const live = await tx.doc(LiveDoc, conversationId);\n await convertPartial(tx, live, conversationId);\n for (const call of unstarted) {\n const result = harnessError(\"aborted\", `Tool ${call.name} was aborted`);\n await appendToolResult(tx, conversationId, call, result, runtime.now());\n }\n endRun(tx, live, runtime.taskId, { status: \"unanswered\", reason: \"aborted\" });\n return { status: \"terminal\", outcome: { status: \"aborted\" } };\n }, context2);\n }\n });\n async function readCalls(runtime, assistant, callIds, context2) {\n const message = (await runtime.entry(AssistantEntry, assistant, context2))?.model?.[0];\n const calls = message?.role === \"assistant\" ? message.content.filter((content) => content.type === \"toolCall\") : [];\n return callIds.flatMap((id) => calls.filter((call) => call.id === id).slice(0, 1));\n }\n function createToolTask(tx, runtime, assistant, callId) {\n return tx.createTask(ToolTask, { assistant, callId }, { ownership: { kind: \"task\", taskId: runtime.taskId } });\n }\n function thresholdCompaction(view, planned, contextWindow, policy) {\n if (!policy.enabled || contextWindow <= 0)\n return void 0;\n const tokens = estimateContext(view, planned.flatMap((entry) => entry.model ?? []));\n const blocking = contextWindow - policy.reserveTokens;\n const background = blocking - policy.backgroundTokens;\n const over = tokens > blocking ? \"blocking\" : policy.backgroundTokens > 0 && tokens > background ? \"background\" : void 0;\n if (over === void 0 || selectCut(view, policy.keepRecentTokens) === void 0)\n return void 0;\n return over;\n }\n async function failModelError(runtime, text, context2) {\n await runtime.commit(async (tx) => {\n const live = await tx.doc(LiveDoc, runtime.conversationId);\n endRun(tx, live, runtime.taskId, { status: \"unanswered\", reason: \"model_error\", detail: text });\n return {\n status: \"terminal\",\n outcome: { status: \"failed\", error: { message: text, detail: { reason: \"model_error\" } } }\n };\n }, context2);\n }\n async function failNoModel(runtime, ref, context2) {\n const message = ref === void 0 ? \"No model is configured\" : `Model ${ref.provider}/${ref.modelId} is not available`;\n await runtime.commit(async (tx) => {\n const live = await tx.doc(LiveDoc, runtime.conversationId);\n endRun(tx, live, runtime.taskId, { status: \"unanswered\", reason: \"no_model\" });\n return { status: \"terminal\", outcome: { status: \"failed\", error: { message, detail: { reason: \"no_model\" } } } };\n }, context2);\n }\n async function convertPartial(tx, live, conversationId) {\n const partial = live.generation?.message;\n if (partial === void 0)\n return;\n const message = copyJson(partial);\n await appendAssistant(tx, conversationId, { ...message, stopReason: \"aborted\" });\n }\n async function streamResponse(runtime, model, messages, options, attempt, context2) {\n const interval = runtime.settings.progress.partialIntervalMs;\n let pending;\n let timer;\n let inFlight;\n let stopped = false;\n const flush = () => {\n timer = void 0;\n const partial = pending;\n pending = void 0;\n if (partial === void 0 || stopped)\n return;\n inFlight = (async () => {\n const message = copyJson(partial, { omitUndefinedProperties: true });\n await runtime.commit(async (tx) => {\n const live = await tx.doc(LiveDoc, runtime.conversationId);\n live.generation ??= { attempt };\n assignJson(live.generation, \"message\", message);\n return void 0;\n }, context2);\n })().catch((error) => {\n if (!runtime.signal.aborted)\n runtime.report(error);\n }).finally(() => {\n inFlight = void 0;\n if (pending !== void 0 && !stopped)\n timer = setTimeout(flush, interval);\n });\n };\n try {\n const events = runtime.models.streamSimple(model, { messages: [...messages] }, options);\n for await (const event of events) {\n if (event.type === \"done\" || event.type === \"error\" || event.partial.content.length === 0)\n continue;\n pending = event.partial;\n if (timer === void 0 && inFlight === void 0)\n timer = setTimeout(flush, interval);\n }\n return await events.result();\n } finally {\n stopped = true;\n clearTimeout(timer);\n await inFlight;\n }\n }\n async function classify(runtime, request, message, context2) {\n runtime.signal.throwIfAborted();\n const conversationId = runtime.conversationId;\n const { attempt, compacted, model: ref, cutoff } = request;\n if (message.stopReason === \"deferred\" && message.deferred !== void 0) {\n const handle = message.deferred;\n const pollAt = Math.max(runtime.now() + (handle.pollAfterMs ?? DEFAULT_POLL_AFTER_MS), request.pollAt === void 0 ? Number.NEGATIVE_INFINITY : request.pollAt + 1);\n await runtime.commit(async (tx) => {\n (await tx.doc(LiveDoc, conversationId)).generation = { attempt, deferred: { pollAt } };\n const checkpoint = {\n phase: \"poll\",\n attempt,\n ...compacted === void 0 ? {} : { compacted },\n model: ref,\n cutoff,\n handle,\n pollAt\n };\n return { status: \"running\", checkpoint };\n }, context2);\n return;\n }\n await runtime.hooks.each(\"afterResponse\", (hook2) => hook2(message, runtime, context2));\n const calls = message.content.filter((content) => content.type === \"toolCall\");\n if (message.stopReason === \"toolUse\" && calls.length > 0) {\n return startToolRound(runtime, request, message, calls, context2);\n }\n if (message.stopReason === \"stop\" || message.stopReason === \"length\" || message.stopReason === \"toolUse\") {\n return answer(runtime, message, context2);\n }\n const settings2 = runtime.settings;\n const overflow = message.stopReason === \"error\" && isContextOverflow(message);\n if (overflow && compacted === void 0 && settings2.compaction.enabled) {\n const policy2 = settings2.compaction;\n const view = await runtime.context(conversationId, context2, { at: cutoff });\n if (selectCut(view, policy2.keepRecentTokens) !== void 0) {\n const text = message.errorMessage ?? \"Context overflow\";\n await runtime.commit(async (tx) => {\n const live = await tx.doc(LiveDoc, conversationId);\n await appendAssistant(tx, conversationId, message);\n delete live.generation;\n const child = await createCompaction(tx, conversationId, { reason: \"overflow\" }, runtime.taskId);\n const checkpoint = { phase: \"prepare\", attempt, compacted: child, overflow: text };\n return { status: \"waiting\", checkpoint, on: [child], policy: \"allSettled\" };\n }, context2);\n return;\n }\n }\n const policy = settings2.retry;\n const retry = message.stopReason === \"error\" && !overflow && isRetryableAssistantError(message) && policy.enabled && attempt <= policy.maxRetries;\n const until = retry ? runtime.now() + retryDelayMs(policy, attempt) : 0;\n await runtime.commit(async (tx) => {\n const live = await tx.doc(LiveDoc, conversationId);\n await appendAssistant(tx, conversationId, message);\n if (retry) {\n live.generation = { attempt, retry: { at: until, error: message.errorMessage ?? \"\" } };\n const checkpoint = {\n phase: \"retry\",\n attempt,\n ...compacted === void 0 ? {} : { compacted },\n until\n };\n return { status: \"running\", checkpoint };\n }\n const text = message.errorMessage ?? `Model response ended with stop reason ${message.stopReason}`;\n endRun(tx, live, runtime.taskId, { status: \"unanswered\", reason: \"model_error\", detail: text });\n return {\n status: \"terminal\",\n outcome: { status: \"failed\", error: { message: text, detail: { reason: \"model_error\" } } }\n };\n }, context2);\n }\n async function answer(runtime, message, context2) {\n let continuation;\n await runtime.hooks.each(\"onYield\", async (hook2) => {\n if (continuation !== void 0)\n return;\n continuation = (await hook2(message, runtime, context2))?.continue;\n });\n const conversationId = runtime.conversationId;\n await runtime.commit(async (tx) => {\n const boundary = await prepareBoundary(tx, conversationId, runtime.settings);\n const live = await tx.doc(LiveDoc, conversationId);\n const entry = await appendAssistant(tx, conversationId, message);\n const result = { status: \"terminal\", outcome: { status: \"completed\", result: { entryId: entry.id } } };\n const { users, reset } = await applyBoundary(tx, boundary, \"final\", runtime.now());\n if (continuation !== void 0 && users.length === 0 && !reset) {\n const user = { role: \"user\", content: continuation, timestamp: runtime.now() };\n await tx.appendEntry(UserEntry, conversationId, { model: [user] });\n handOver(live, runtime.taskId, await createGeneration(tx, conversationId));\n delete live.generation;\n return result;\n }\n endRun(tx, live, runtime.taskId, { status: \"done\", answer: entry.id });\n if (users.length > 0)\n await startRun(tx, conversationId, live, users);\n return result;\n }, context2);\n }\n async function startToolRound(runtime, request, message, calls, context2) {\n const conversationId = runtime.conversationId;\n const messages = request.messages ?? (await runtime.context(conversationId, context2, { at: request.cutoff })).messages;\n const offered = new Set(getCurrentTools(messages).map((tool) => tool.name));\n const tools = (await runtime.agent(context2)).tools;\n const sequential = runtime.settings.toolExecution === \"sequential\" || calls.some((call) => offered.has(call.name) && tools.find((tool) => tool.name === call.name)?.executionMode === \"sequential\");\n await runtime.commit(async (tx) => {\n const live = await tx.doc(LiveDoc, conversationId);\n const entry = await appendAssistant(tx, conversationId, message);\n const slots = [];\n const tools2 = [];\n const pending = [];\n for (const call of calls) {\n if (!offered.has(call.name)) {\n const unavailable = harnessError(\"tool_unavailable\", `Tool ${call.name} is not available`);\n const result = await appendToolResult(tx, conversationId, call, unavailable, runtime.now());\n slots.push({ callId: call.id, name: call.name, status: \"done\", entry: result.id });\n continue;\n }\n if (sequential && tools2.length > 0) {\n pending.push(call.id);\n slots.push({ callId: call.id, name: call.name, status: \"pending\" });\n continue;\n }\n const taskId = await createToolTask(tx, runtime, entry.id, call.id);\n tools2.push(taskId);\n slots.push({ callId: call.id, name: call.name, taskId, status: \"pending\" });\n }\n delete live.generation;\n live.tools = slots;\n const checkpoint = { phase: \"tools\", assistant: entry.id, tools: tools2, pending };\n return { status: \"waiting\", checkpoint, on: tools2, policy: \"allSettled\" };\n }, context2);\n }\n async function finishToolRound(runtime, assistant, tools, context2) {\n const conversationId = runtime.conversationId;\n const controls = /* @__PURE__ */ new Map();\n const outcomes = await runtime.outcomes(tools, context2);\n tools.forEach((id, index3) => {\n const outcome = outcomes[index3];\n controls.set(id, outcome.status === \"completed\" ? outcome.result.control : void 0);\n });\n const slots = (await runtime.snapshot(LiveDoc, conversationId, context2))?.tools ?? [];\n const results = slots.flatMap((slot) => slot.entry === void 0 ? [] : [slot.entry]);\n await runtime.hooks.each(\"afterTools\", (hook2) => hook2(assistant, results, runtime, context2));\n const terminate = slots.length > 0 && slots.every((slot) => slot.taskId !== void 0 && controls.get(slot.taskId)?.terminate === true);\n const added = [...controls.values()].flatMap((control) => control?.addTools ?? []);\n const handoff = [...controls.values()].findLast((control) => control?.handoff !== void 0)?.handoff;\n await runtime.commit(async (tx) => {\n const boundary = await prepareBoundary(tx, conversationId, runtime.settings);\n if (added.length > 0)\n await addTools(tx, conversationId, added);\n const live = await tx.doc(LiveDoc, conversationId);\n const now = runtime.now();\n if (terminate || handoff !== void 0) {\n if (handoff !== void 0) {\n const message = { role: \"user\", content: handoff, timestamp: now };\n const entry = await tx.appendEntry(ResetEntry, conversationId, { head: \"self\", model: [message] });\n boundary.head = entry.id;\n }\n const { users } = await applyBoundary(tx, boundary, \"final\", now);\n endRun(tx, live, runtime.taskId, { status: \"done\", answer: assistant });\n if (users.length > 0)\n await startRun(tx, conversationId, live, users);\n } else {\n const { users, reset } = await applyBoundary(tx, boundary, \"postTools\", now);\n if (reset) {\n endRun(tx, live, runtime.taskId, { status: \"unanswered\", reason: \"reset\" });\n if (users.length > 0)\n await startRun(tx, conversationId, live, users);\n } else {\n delete live.tools;\n if (live.run?.taskId === runtime.taskId)\n live.run.inputs.push(...users);\n handOver(live, runtime.taskId, await createGeneration(tx, conversationId));\n }\n }\n return { status: \"terminal\", outcome: { status: \"completed\", result: { entryId: assistant } } };\n }, context2);\n }\n async function appendAssistant(tx, conversationId, message) {\n await recordUsage(tx, conversationId, \"models\", `${message.provider}/${message.model}`, message.usage);\n return tx.appendEntry(AssistantEntry, conversationId, { model: [message] });\n }\n async function startRun(tx, conversationId, live, inputs) {\n live.run = { taskId: await createGeneration(tx, conversationId), inputs };\n }\n function createGeneration(tx, conversationId) {\n return tx.createTask(GenerationTask, {}, { ownership: { kind: \"conversation\" }, conversationId });\n }\n function handOver(live, from, to) {\n if (live.run?.taskId === from)\n live.run.taskId = to;\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/live.js\n var LiveDoc = defineDoc({\n kind: \"pi.live\",\n version: 1,\n scope: \"conversation\",\n history: \"latest\",\n fork: \"initial\",\n initial: () => ({}),\n // REMINDER: a complete base whenever nothing runs (spec §8.2): no generation and no running tool slot. That holds\n // while idle, in the commit handing a generation over to its tool round, and between tools, so the delta chain\n // spans at most one generation or the overlapping execution of one round's tools. A slot holds output only while\n // running, so every base is small. Do not add a delta-count bound; the tool output benchmark checks this rule.\n checkpointWhen: (value) => value.generation === void 0 && !(value.tools ?? []).some((slot) => slot.status === \"running\")\n });\n var RUN_TASK_KINDS = /* @__PURE__ */ new Set([\"pi.generation\"]);\n var TOOL_TASK_KIND = \"pi.tool\";\n var COMPACTION_TASK_KIND = \"pi.compaction\";\n function endRun(tx, live, taskId, settlement) {\n if (live.run?.taskId === taskId) {\n for (const id of live.run.inputs)\n tx.settleSubmission(id, settlement);\n delete live.run;\n }\n delete live.generation;\n delete live.tools;\n }\n function addCompactionStatus(live, status) {\n live.compactions ??= [];\n live.compactions.push(status);\n }\n function compactionStatus(live, taskId) {\n return live.compactions?.find((status) => status.taskId === taskId);\n }\n function removeCompactionStatus(live, taskId) {\n const statuses = live.compactions;\n if (statuses === void 0)\n return;\n const index3 = statuses.findIndex((status) => status.taskId === taskId);\n if (index3 >= 0)\n statuses.splice(index3, 1);\n if (statuses.length === 0)\n delete live.compactions;\n }\n function toolSlot(live, taskId) {\n return live.tools?.find((slot) => slot.taskId === taskId);\n }\n function finishSlot(slot, entry) {\n slot.status = \"done\";\n if (entry !== void 0)\n slot.entry = entry;\n clearProgress(slot);\n }\n function clearProgress(slot) {\n delete slot.output;\n delete slot.droppedBytes;\n delete slot.droppedLines;\n delete slot.details;\n delete slot.diagnostics;\n }\n async function settleSchedulerOutcome(tx, record, outcome) {\n if (record.kind === TOOL_TASK_KIND) {\n const slot = toolSlot(await tx.doc(LiveDoc, record.conversationId), record.id);\n if (slot !== void 0)\n finishSlot(slot, void 0);\n return;\n }\n if (record.kind === COMPACTION_TASK_KIND) {\n removeCompactionStatus(await tx.doc(LiveDoc, record.conversationId), record.id);\n return;\n }\n if (!RUN_TASK_KINDS.has(record.kind))\n return;\n const live = await tx.doc(LiveDoc, record.conversationId);\n if (live.run?.taskId !== record.id)\n return;\n await convertPartial(tx, live, record.conversationId);\n endRun(tx, live, record.id, outcome.status === \"faulted\" ? { status: \"unanswered\", reason: \"faulted\", detail: outcome.error.message } : { status: \"unanswered\", reason: outcome.reason });\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/util.js\n var Waiters = class {\n #sets = /* @__PURE__ */ new Map();\n add(key, context2) {\n const signal = context2.abortSignal;\n if (signal?.aborted)\n return Promise.reject(signal.reason);\n const waiter = Promise.withResolvers();\n const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set();\n this.#sets.set(key, set.add(waiter));\n if (signal !== void 0) {\n const onAbort = () => {\n set.delete(waiter);\n if (set.size === 0 && this.#sets.get(key) === set)\n this.#sets.delete(key);\n waiter.reject(signal.reason);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n const detach = () => signal.removeEventListener(\"abort\", onAbort);\n waiter.promise.then(detach, detach);\n }\n return waiter.promise;\n }\n keys() {\n return [...this.#sets.keys()];\n }\n resolve(key, value) {\n const set = this.#sets.get(key);\n this.#sets.delete(key);\n for (const waiter of set ?? [])\n waiter.resolve(value);\n }\n rejectAll(error) {\n const sets = [...this.#sets.values()];\n this.#sets.clear();\n for (const set of sets)\n for (const waiter of set)\n waiter.reject(error);\n }\n };\n async function scanAll(scan) {\n const items = [];\n let cursor;\n do {\n const page2 = await scan(cursor);\n items.push(...page2.items);\n cursor = page2.next;\n } while (cursor !== void 0);\n return items;\n }\n function closedError() {\n return new Error(\"Harness is closed\");\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/submissions.js\n var Submissions = class {\n #session;\n #storage;\n #now;\n /** Read at each admission, on the Session line. */\n #queueModes;\n /** Enable task scheduling; submitting or waiting asks for progress. */\n #resume;\n #waiters = new Waiters();\n #closed = false;\n constructor(session, storage, now, queueModes, resume) {\n this.#session = session;\n this.#storage = storage;\n this.#now = now;\n this.#queueModes = queueModes;\n this.#resume = resume;\n session.subscribeCommits((publication) => this.#observe(publication));\n session.subscribeClose(() => {\n this.#closed = true;\n this.#waiters.rejectAll(closedError());\n });\n }\n /** Admit a submission in one commit; see `admitSubmission()`. */\n async submit(conversationId, draft, context2) {\n this.#resume();\n const id = await this.#session.commitWith((tx) => admitSubmission(tx, conversationId, draft, this.#now(), this.#queueModes()), context2);\n return new SubmissionHandle(id, this);\n }\n /** Handle for an existing submission, or `undefined`. */\n async get(id, context2) {\n const record = await this.#session.readOnLine(() => this.#storage.submission(id, context2));\n return record === void 0 ? void 0 : new SubmissionHandle(record.id, this);\n }\n async status(id, context2) {\n const record = await this.#session.readOnLine(() => this.#storage.submission(id, context2));\n if (record === void 0)\n throw new Error(`Submission ${id} does not exist`);\n return record;\n }\n async wait(id, context2) {\n this.#resume();\n const found = await this.#session.readOnLine(async () => {\n const record = await this.#storage.submission(id, context2);\n if (record === void 0)\n throw new Error(`Submission ${id} does not exist`);\n if (isSettled(record))\n return { promise: Promise.resolve(record) };\n if (this.#closed)\n throw closedError();\n return { promise: this.#waiters.add(id, context2) };\n });\n return found.promise;\n }\n /** Withdraw a queued submission and remove its inbox item; placed inputs and settled submissions are reported. */\n abort(id, context2, conversationId) {\n return this.#session.commitWith(async (tx) => {\n const record = await tx.submission(id);\n if (record === void 0 || conversationId !== void 0 && record.conversationId !== conversationId) {\n return \"not_found\";\n }\n if (record.status === \"queued\") {\n tx.settleSubmission(id, { status: \"unanswered\", reason: \"aborted\" });\n await removeInboxItem(tx, record.conversationId, id);\n return \"aborted\";\n }\n return record.status === \"placed\" ? \"already_placed\" : \"settled\";\n }, context2);\n }\n #observe(publication) {\n for (const change of publication.changes) {\n if (change.type !== \"submission\" || !isSettled(change.value))\n continue;\n this.#waiters.resolve(change.value.id, change.value);\n }\n }\n };\n var SubmissionHandle = class {\n id;\n #submissions;\n constructor(id, submissions) {\n this.id = id;\n this.#submissions = submissions;\n }\n status(context2) {\n return this.#submissions.status(this.id, context2);\n }\n wait(context2) {\n return this.#submissions.wait(this.id, context2);\n }\n async abort(context2) {\n const result = await this.#submissions.abort(this.id, context2);\n if (result === \"not_found\")\n throw new Error(`Submission ${this.id} does not exist`);\n return result;\n }\n };\n function isSettled(record) {\n return record.status === \"done\" || record.status === \"unanswered\";\n }\n async function admitSubmission(tx, conversationId, draft, now, queueModes) {\n if (draft.requestId !== void 0) {\n const existing = await tx.submissionByRequest(conversationId, draft.requestId);\n if (existing !== void 0) {\n if (existing.type !== draft.type) {\n throw new Error(`Request ${draft.requestId} already identifies a submission of type ${existing.type}`);\n }\n return existing.id;\n }\n }\n const live = await tx.doc(LiveDoc, conversationId);\n const busy = live.run !== void 0;\n if (busy && draft.type === \"input\" && draft.whenBusy === \"reject\")\n throw new ConversationBusy(conversationId);\n const requestId = draft.requestId === void 0 ? {} : { requestId: draft.requestId };\n const boundary = busy ? void 0 : await prepareBoundary(tx, conversationId, queueModes);\n if (boundary === void 0 || boundary.inbox.items.length > 0) {\n const { id: id2 } = await tx.createSubmission({\n conversationId,\n ...requestId,\n type: draft.type,\n status: \"queued\"\n });\n const value = copyJson(draft.type === \"write\" ? draft.entry : draft.content, {\n omitUndefinedProperties: true\n });\n const items = (boundary?.inbox ?? await tx.doc(InboxDoc, conversationId)).items;\n if (draft.type === \"write\")\n items.push({ id: id2, mode: \"write\", entry: value });\n else {\n const mode = draft.whenBusy === \"steer\" ? \"steer\" : \"followUp\";\n items.push({ id: id2, mode, content: value });\n }\n if (boundary === void 0)\n return id2;\n const { users } = await applyBoundary(tx, boundary, \"final\", now);\n if (users.length > 0)\n await startRun(tx, conversationId, live, users);\n return id2;\n }\n if (draft.type === \"write\") {\n if (isStale(boundary, draft.entry)) {\n const stale = { status: \"unanswered\", reason: \"stale\" };\n return (await tx.createSubmission({ conversationId, ...requestId, type: \"write\", ...stale })).id;\n }\n const entry2 = await tx.appendEntry(conversationId, draft.entry);\n const write = { conversationId, ...requestId, type: \"write\", status: \"done\", entry: entry2.id };\n return (await tx.createSubmission(write)).id;\n }\n const message = { role: \"user\", content: draft.content, timestamp: now };\n const entry = await tx.appendEntry(UserEntry, conversationId, { model: [message] });\n const input = { conversationId, ...requestId, type: \"input\", status: \"placed\", entry: entry.id };\n const { id } = await tx.createSubmission(input);\n await startRun(tx, conversationId, live, [id]);\n return id;\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/compaction.js\n var TOOL_RESULT_MAX_CHARS = 2e3;\n var SUMMARY_PREFIX = \"The conversation history before this point was compacted into the following summary:\\n\\n<summary>\\n\";\n var SUMMARY_SUFFIX = \"\\n</summary>\";\n var SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;\n var SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work. If the conversation starts with an earlier summary, preserve its information and fold the newer messages into it.\n\nUse this EXACT format:\n\n## Goal\n[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned by user]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Current work]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Any data, examples, or references needed to continue]\n- [Or \"(none)\" if not applicable]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n var CompactionTask = defineTask({\n name: \"pi.compaction\",\n version: 1,\n initial: () => ({ phase: \"select\" }),\n phases: {\n select: async (task, runtime, context2) => {\n const { conversationId } = runtime;\n const agent = await runtime.agent(context2);\n const settings2 = runtime.settings;\n const ref = agent.model;\n const model = ref === void 0 ? void 0 : runtime.models.getModel(ref.provider, ref.modelId);\n if (ref === void 0 || model === void 0)\n return failNoModel2(runtime, ref, context2);\n const policy = settings2.compaction;\n const view = await runtime.context(conversationId, context2);\n const cut = selectCut(view, policy.keepRecentTokens);\n if (cut === void 0)\n return complete(runtime, context2);\n const firstKept = view.entries[cut].id;\n const { reason, instructions } = task.input;\n const compaction = {\n reason,\n entries: view.entries.slice(0, cut),\n messages: summarizedMessages(view, cut),\n firstKept,\n ...instructions === void 0 ? {} : { instructions }\n };\n let decision;\n await runtime.hooks.each(\"beforeCompact\", async (hook2) => {\n if (decision === void 0)\n decision = await hook2(compaction, runtime, context2);\n });\n if (decision !== void 0 && \"decline\" in decision)\n return complete(runtime, context2);\n if (decision !== void 0)\n return place(runtime, firstKept, decision.summary, context2);\n const request = {\n attempt: 1,\n model: ref,\n thinkingLevel: agent.thinkingLevel,\n streamOptions: settings2.stream,\n maxTokens: Math.min(Math.floor(0.8 * policy.reserveTokens), model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY),\n tail: view.entries.reduce((tail, entry) => entry.id > tail ? entry.id : tail, firstKept),\n firstKept\n };\n await runtime.commit(() => ({ status: \"running\", checkpoint: { phase: \"summarize\", ...request } }), context2);\n },\n summarize: async (task, runtime, context2) => {\n const { phase: _, ...request } = task.state.checkpoint;\n const { model: ref, thinkingLevel, streamOptions, maxTokens, tail, firstKept, attempt } = request;\n const model = runtime.models.getModel(ref.provider, ref.modelId);\n if (model === void 0)\n return failNoModel2(runtime, ref, context2);\n const view = await runtime.context(runtime.conversationId, context2, { at: tail });\n const cut = view.entries.findIndex((entry) => entry.id === firstKept);\n const now = runtime.now();\n const messages = [\n { role: \"system\", content: SUMMARIZATION_SYSTEM_PROMPT, timestamp: now },\n {\n role: \"user\",\n content: [{ type: \"text\", text: summaryPrompt(summarizedMessages(view, cut), task.input.instructions) }],\n timestamp: now\n }\n ];\n const { deferred: _deferred, ...forwarded } = streamOptions;\n const options = {\n ...forwarded,\n cacheRetention: \"none\",\n maxTokens,\n signal: runtime.signal,\n sessionId: await ensureProviderSessionId(runtime, context2),\n ...thinkingLevel === \"off\" ? {} : { reasoning: thinkingLevel }\n };\n const message = await runtime.models.completeSimple(model, { messages }, options);\n runtime.signal.throwIfAborted();\n const summary = summaryText(message);\n const policy = runtime.settings.retry;\n const retry = message.stopReason === \"error\" && isRetryableAssistantError(message) && policy.enabled && attempt <= policy.maxRetries;\n const until = retry ? runtime.now() + retryDelayMs(policy, attempt) : 0;\n await runtime.commit(async (tx, current) => {\n await recordUsage(tx, runtime.conversationId, \"models\", `${message.provider}/${message.model}`, message.usage);\n const live = await tx.doc(LiveDoc, runtime.conversationId);\n if (summary !== void 0)\n return placeSummary(tx, runtime, current, live, firstKept, summary);\n if (retry) {\n const status = compactionStatus(live, runtime.taskId);\n if (status !== void 0)\n status.retry = { at: until, error: message.errorMessage ?? \"\" };\n return { status: \"running\", checkpoint: { phase: \"retry\", ...request, until } };\n }\n removeCompactionStatus(live, runtime.taskId);\n const text = summaryFailure(message);\n return {\n status: \"terminal\",\n outcome: { status: \"failed\", error: { message: text, detail: { reason: \"model_error\" } } }\n };\n }, context2);\n },\n retry: async (task, runtime, context2) => {\n const { phase: _, until, ...request } = task.state.checkpoint;\n await runtime.sleep(until, context2);\n const attempt = request.attempt + 1;\n await runtime.commit(async (tx) => {\n const status = compactionStatus(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n if (status !== void 0) {\n status.attempt = attempt;\n delete status.retry;\n }\n return { status: \"running\", checkpoint: { phase: \"summarize\", ...request, attempt } };\n }, context2);\n }\n },\n abort: async (_task, runtime, context2) => {\n await runtime.commit(async (tx) => {\n removeCompactionStatus(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n return { status: \"terminal\", outcome: { status: \"aborted\" } };\n }, context2);\n }\n });\n async function createCompaction(tx, conversationId, input, owner) {\n const ownership = owner === void 0 ? { kind: \"conversation\" } : { kind: \"task\", taskId: owner };\n const background = owner === void 0 && input.reason !== \"manual\";\n const taskId = await tx.createTask(CompactionTask, input, { ownership, conversationId, background });\n const status = { taskId, reason: input.reason, blocking: owner !== void 0, attempt: 1 };\n addCompactionStatus(await tx.doc(LiveDoc, conversationId), status);\n return taskId;\n }\n function selectCut(view, keepRecentTokens) {\n const { contributions } = view;\n const start = view.head === void 0 ? 0 : 1;\n const candidates = [];\n for (let index3 = start; index3 < contributions.length; index3++) {\n if (isCandidate(contributions, index3))\n candidates.push(index3);\n }\n let kept = 0;\n let cut;\n for (let index3 = contributions.length - 1; index3 >= start; index3--) {\n for (const message of contributions[index3])\n kept += estimateMessageTokens(message);\n if (kept < keepRecentTokens)\n continue;\n cut = candidates.find((candidate) => candidate >= index3) ?? candidates.at(-1);\n break;\n }\n if (cut === void 0)\n return void 0;\n for (let index3 = start; index3 < cut; index3++)\n if (contributions[index3].length > 0)\n return cut;\n return void 0;\n }\n function isCandidate(contributions, index3) {\n const first = contributions[index3][0];\n if (first?.role === \"assistant\")\n return true;\n if (first?.role !== \"user\")\n return false;\n let calls = /* @__PURE__ */ new Set();\n for (let before = index3 - 1; before >= 0; before--) {\n const assistant = contributions[before].findLast((message) => message.role === \"assistant\");\n if (assistant === void 0)\n continue;\n calls = new Set(assistant.content.flatMap((content) => content.type === \"toolCall\" ? [content.id] : []));\n break;\n }\n if (calls.size === 0)\n return true;\n for (let after = index3; after < contributions.length; after++) {\n for (const [position, message] of contributions[after].entries()) {\n if (message.role === \"assistant\" && (after > index3 || position > 0))\n return true;\n if (message.role === \"toolResult\" && calls.has(message.toolCallId))\n return false;\n }\n }\n return true;\n }\n function summarizedMessages(view, cut) {\n return orderToolResults(view.contributions.slice(0, cut).flat());\n }\n function estimateContext(view, extra) {\n let measured;\n const after = view.head?.id ?? Number.NEGATIVE_INFINITY;\n for (let index3 = view.entries.length - 1; index3 >= 0 && measured === void 0; index3--) {\n if (view.entries[index3].id <= after)\n continue;\n measured = view.contributions[index3].findLast((message) => message.role === \"assistant\" && calculateContextTokens(message.usage) > 0);\n }\n const from = measured === void 0 ? 0 : view.messages.lastIndexOf(measured) + 1;\n let tokens = measured === void 0 ? 0 : calculateContextTokens(measured.usage);\n for (const message of view.messages.slice(from))\n tokens += estimateMessageTokens(message);\n for (const message of extra)\n tokens += estimateMessageTokens(message);\n return tokens;\n }\n function summaryText(message) {\n if (message.stopReason !== \"stop\" || message.content.some((content) => content.type === \"toolCall\"))\n return void 0;\n const text = message.content.flatMap((content) => content.type === \"text\" ? [content.text] : []).join(\"\\n\").trim();\n return text.length === 0 ? void 0 : text;\n }\n function summaryFailure(message) {\n if (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n return `Summarization failed: ${message.errorMessage ?? message.stopReason}`;\n }\n if (message.stopReason === \"length\")\n return \"Summarization hit the token limit; the summary is incomplete\";\n if (message.content.some((content) => content.type === \"toolCall\"))\n return \"Summarization attempted to call a tool\";\n return \"Summarization produced no text\";\n }\n function summaryPrompt(messages, instructions) {\n const focus = instructions === void 0 ? \"\" : `\n\nAdditional focus: ${instructions}`;\n return `<conversation>\n${serializeConversation(messages)}\n</conversation>\n\n${SUMMARIZATION_PROMPT}${focus}`;\n }\n function serializeConversation(messages) {\n const parts2 = [];\n for (const message of messages) {\n if (message.role === \"user\") {\n const text = contentText2(message.content);\n if (text.length > 0)\n parts2.push(`[User]: ${text}`);\n } else if (message.role === \"assistant\") {\n const thinking = message.content.flatMap((content) => content.type === \"thinking\" ? [content.thinking] : []);\n const text = message.content.flatMap((content) => content.type === \"text\" ? [content.text] : []);\n const calls = message.content.flatMap((content) => content.type === \"toolCall\" ? [\n `${content.name}(${Object.entries(content.arguments).map(([key, value]) => `${key}=${JSON.stringify(value)}`).join(\", \")})`\n ] : []);\n if (thinking.length > 0)\n parts2.push(`[Assistant thinking]: ${thinking.join(\"\\n\")}`);\n if (text.length > 0)\n parts2.push(`[Assistant]: ${text.join(\"\\n\")}`);\n if (calls.length > 0)\n parts2.push(`[Assistant tool calls]: ${calls.join(\"; \")}`);\n } else if (message.role === \"toolResult\") {\n const text = contentText2(message.content);\n if (text.length > 0)\n parts2.push(`[Tool result]: ${truncate(text, TOOL_RESULT_MAX_CHARS)}`);\n }\n }\n return parts2.join(\"\\n\\n\");\n }\n function contentText2(content) {\n if (typeof content === \"string\")\n return content;\n return content.flatMap((block) => block.type === \"text\" && block.text !== void 0 ? [block.text] : []).join(\"\\n\");\n }\n function truncate(text, maxChars) {\n if (text.length <= maxChars)\n return text;\n return `${text.slice(0, maxChars)}\n\n[... ${text.length - maxChars} more characters truncated]`;\n }\n async function place(runtime, firstKept, summary, context2) {\n await runtime.commit(async (tx, current) => placeSummary(tx, runtime, current, await tx.doc(LiveDoc, runtime.conversationId), firstKept, summary), context2);\n }\n async function placeSummary(tx, runtime, current, live, firstKept, summary) {\n removeCompactionStatus(live, runtime.taskId);\n const text = `${SUMMARY_PREFIX}${summary}${SUMMARY_SUFFIX}`;\n const entry = {\n kind: CompactionEntry.kind,\n head: firstKept,\n model: [{ role: \"user\", content: [{ type: \"text\", text }], timestamp: runtime.now() }],\n data: { reason: current.input.reason }\n };\n const result = current.owner === void 0 ? {\n submissionId: await admitSubmission(tx, runtime.conversationId, { type: \"write\", requestId: `compaction:${runtime.taskId}`, entry }, runtime.now(), runtime.settings)\n } : { entryId: (await tx.appendEntry(runtime.conversationId, entry)).id };\n return { status: \"terminal\", outcome: { status: \"completed\", result } };\n }\n async function complete(runtime, context2) {\n await runtime.commit(async (tx) => {\n removeCompactionStatus(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n return { status: \"terminal\", outcome: { status: \"completed\", result: {} } };\n }, context2);\n }\n async function failNoModel2(runtime, ref, context2) {\n const message = ref === void 0 ? \"No model is configured\" : `Model ${ref.provider}/${ref.modelId} is not available`;\n await runtime.commit(async (tx) => {\n removeCompactionStatus(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n return { status: \"terminal\", outcome: { status: \"failed\", error: { message, detail: { reason: \"no_model\" } } } };\n }, context2);\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/define.js\n function defineExtension(extension) {\n return extension;\n }\n function defineTool(tool) {\n return tool;\n }\n function section(key, render, options) {\n return options?.tag === void 0 ? { key, render } : { key, render, tag: options.tag };\n }\n function hook(task, handlers) {\n return { task: task.definition.name, handlers };\n }\n function wrapTool(tool, wrapper) {\n return { tool: tool.name, wrap: wrapper };\n }\n function wrapSection(key, wrapper) {\n return { section: key, wrap: wrapper };\n }\n\n // node_modules/@earendil-works/pi-durable/dist/session/observation.js\n var MAX_PENDING_WATCH_FRAMES = 100;\n var RETIREMENT_OPERATIONS = [[\"r\", null]];\n var CommittedStateSource = class {\n #attachments = /* @__PURE__ */ new Set();\n #release;\n /** Released on disposal. */\n #value;\n #cursor = 0;\n #retired = false;\n #closed = false;\n constructor(value, release) {\n this.#value = value;\n this.#release = release;\n }\n attach() {\n if (this.#closed)\n throw new Error(\"State source is closed\");\n const attachment = new SessionSourceAttachment({ value: this.#value, cursor: this.#cursor }, () => {\n this.#attachments.delete(attachment);\n if (this.#attachments.size === 0)\n this.#finishDisposal();\n });\n this.#attachments.add(attachment);\n return attachment;\n }\n advance(value, ops, context2) {\n if (this.#closed || this.#retired)\n return;\n this.#value = value;\n this.#cursor += 1;\n if (value === null)\n this.#retired = true;\n const frame = {\n cursor: this.#cursor,\n value,\n ops,\n context: context2\n };\n for (const attachment of [...this.#attachments])\n attachment.publish(frame);\n }\n closeSession() {\n if (this.#closed)\n return;\n for (const attachment of [...this.#attachments])\n attachment.dispose();\n this.#finishDisposal();\n }\n #finishDisposal() {\n if (this.#closed)\n return;\n this.#closed = true;\n this.#value = void 0;\n const release = this.#release;\n this.#release = void 0;\n release?.();\n }\n };\n var SessionSourceAttachment = class {\n snapshot;\n #release;\n #frames = [];\n #listener;\n #activated = false;\n #disposed = false;\n #scheduled = false;\n #delivering = false;\n constructor(snapshot, release) {\n this.snapshot = snapshot;\n this.#release = release;\n }\n activate(listener) {\n if (this.#activated)\n throw new Error(\"State attachment is already active\");\n if (this.#disposed)\n throw new Error(\"State attachment is disposed\");\n this.#activated = true;\n this.#listener = listener;\n this.#drain();\n }\n publish(frame) {\n if (this.#disposed)\n return;\n this.#frames.push(frame);\n if (!this.#activated || this.#delivering || this.#scheduled)\n return;\n this.#scheduled = true;\n queueMicrotask(() => {\n this.#scheduled = false;\n if (this.#disposed)\n return;\n try {\n this.#drain();\n } catch {\n this.dispose();\n }\n });\n }\n dispose() {\n if (this.#disposed)\n return;\n this.#disposed = true;\n this.#frames.length = 0;\n this.#listener = void 0;\n const release = this.#release;\n this.#release = void 0;\n release?.();\n }\n #drain() {\n const listener = this.#listener;\n if (listener === void 0 || this.#delivering || this.#disposed)\n return;\n this.#delivering = true;\n try {\n while (!this.#disposed) {\n const frame = this.#frames.shift();\n if (frame === void 0)\n break;\n listener(frame);\n }\n } finally {\n this.#delivering = false;\n }\n }\n };\n var CommittedWatch = class {\n #detach;\n #replace;\n #closedPromise;\n #pending = [];\n #resolveClosed;\n #value;\n #listener;\n #started = false;\n #scheduled = false;\n #running = false;\n #detached = false;\n #retired = false;\n #end;\n #resolved = false;\n #cancellationSignal;\n #cancellationListener;\n /** `replace` gives the value an overflow delivers; by default the newest value. */\n constructor(value, detach, replace) {\n this.#value = value;\n this.#detach = detach;\n this.#replace = replace;\n this.#closedPromise = new Promise((resolve2) => {\n this.#resolveClosed = resolve2;\n });\n }\n get value() {\n return this.#value;\n }\n get closed() {\n return this.#closedPromise;\n }\n start(listener) {\n if (this.#started)\n throw new Error(\"Watch is already started\");\n if (this.#end !== void 0)\n throw new Error(\"Watch is stopped\");\n this.#started = true;\n this.#listener = listener;\n if (this.#pending.length > 0)\n this.#schedule();\n }\n stop() {\n this.#terminate({ reason: \"stopped\" });\n return this.#closedPromise;\n }\n observeCancellation(signal) {\n if (this.#cancellationSignal !== void 0)\n throw new Error(\"Watch cancellation is already installed\");\n if (this.#end !== void 0)\n return;\n this.#cancellationSignal = signal;\n this.#cancellationListener = () => this.cancel();\n signal.addEventListener(\"abort\", this.#cancellationListener, { once: true });\n if (signal.aborted)\n this.cancel();\n }\n cancel() {\n this.#terminate({ reason: \"cancelled\" });\n }\n closeSession() {\n this.#terminate({ reason: \"session_closed\" });\n }\n advance(value, ops, context2) {\n if (this.#end !== void 0 || this.#retired)\n return;\n if (value === null)\n this.#retired = true;\n if (this.#pending.length >= MAX_PENDING_WATCH_FRAMES) {\n this.#pending.length = 0;\n const replacement = this.#replace?.() ?? value;\n this.#pending.push({ value: replacement, ops: [[\"r\", replacement]], context: context2 });\n } else {\n this.#pending.push({ value, ops, context: context2 });\n }\n if (this.#started)\n this.#schedule();\n }\n #schedule() {\n if (this.#scheduled || this.#running || this.#end !== void 0)\n return;\n this.#scheduled = true;\n queueMicrotask(() => {\n this.#scheduled = false;\n void this.#drain();\n });\n }\n async #drain() {\n if (this.#running || this.#end !== void 0 || !this.#started) {\n this.#finishIfReady();\n return;\n }\n this.#running = true;\n try {\n while (this.#end === void 0) {\n const frame = this.#pending.shift();\n if (frame === void 0)\n break;\n this.#value = frame.value;\n const deliveryContext = withoutAbortSignal(frame.context);\n try {\n await this.#listener(frame.value, frame.ops, deliveryContext);\n } catch (error) {\n if (this.#end === void 0) {\n this.#terminate({ reason: \"listener_error\", error: toError2(error) });\n }\n break;\n }\n if (frame.value === null) {\n this.#terminate({ reason: \"retired\" });\n break;\n }\n }\n } finally {\n this.#running = false;\n if (this.#end === void 0 && this.#pending.length > 0)\n this.#schedule();\n this.#finishIfReady();\n }\n }\n #terminate(end) {\n if (this.#end !== void 0)\n return;\n this.#end = end;\n this.#detachNow();\n this.#pending.length = 0;\n this.#finishIfReady();\n }\n #detachNow() {\n if (this.#detached)\n return;\n this.#detached = true;\n this.#detach();\n }\n #finishIfReady() {\n if (this.#resolved || this.#end === void 0)\n return;\n this.#resolved = true;\n if (this.#cancellationSignal !== void 0 && this.#cancellationListener !== void 0) {\n this.#cancellationSignal.removeEventListener(\"abort\", this.#cancellationListener);\n }\n this.#resolveClosed(this.#end);\n }\n };\n function toError2(error) {\n return error instanceof Error ? error : new Error(String(error));\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/view.js\n var MOUNTED = [\n AgentDoc,\n LiveDoc,\n InboxDoc,\n ProviderDoc,\n UsageDoc\n ];\n var MOUNTED_KINDS = new Set(MOUNTED.map((token) => token.definition.kind));\n var VIEWS = /* @__PURE__ */ new WeakMap();\n function conversationViews(harness2) {\n const views = VIEWS.get(harness2);\n if (views === void 0)\n throw new Error(\"Not a Harness\");\n return views;\n }\n var ConversationViews = class {\n #session;\n #storage;\n #mounts = /* @__PURE__ */ new Map();\n #closed = false;\n constructor(session, storage) {\n this.#session = session;\n this.#storage = storage;\n VIEWS.set(session, this);\n session.subscribeCommits((publication, context2) => {\n for (const [id, mount] of this.#mounts)\n advance(id, mount, publication, context2);\n });\n session.subscribeClose(() => {\n this.#closed = true;\n for (const mount of this.#mounts.values())\n for (const observer of [...mount.observers])\n observer.closeSession();\n this.#mounts.clear();\n });\n }\n /** A disposable read-only Chord state of the view. */\n async state(id, context2) {\n const { observer, detach } = await this.attach(id, (value, release) => new CommittedStateSource(value, release), context2);\n try {\n return replicatedState(observer);\n } catch (error) {\n detach();\n throw error;\n }\n }\n /** A serialized exact-frame watch of the view; cancelling `context` stops it. */\n async watch(id, context2) {\n const { observer } = await this.attach(id, (value, release) => new CommittedWatch(value, release), context2);\n const signal = context2.abortSignal;\n if (signal?.aborted) {\n observer.cancel();\n throw signal.reason;\n }\n if (signal !== void 0)\n observer.observeCancellation(signal);\n return observer;\n }\n /**\n * Register an observer created from the current revision, atomically on the Session line: it sees every later\n * publication and nothing earlier. `create` may read committed Storage, still on the line. `release` drops it, and\n * the mount with its last observer.\n */\n attach(id, create, context2) {\n return this.#session.readOnLine(async () => {\n const mount = this.#mounts.get(id) ?? await this.#build(id, context2);\n const detach = () => {\n mount.observers.delete(observer);\n if (mount.observers.size === 0 && this.#mounts.get(id) === mount)\n this.#mounts.delete(id);\n };\n const observer = await create(mount.value, detach, this.#storage);\n if (this.#closed)\n throw closedError();\n context2.abortSignal?.throwIfAborted();\n this.#mounts.set(id, mount);\n mount.observers.add(observer);\n return { observer, detach };\n });\n }\n async #build(id, context2) {\n const conversation2 = await this.#storage.conversation(id, context2);\n if (conversation2 === void 0)\n throw new Error(`Conversation ${id} does not exist`);\n const bounds = await captureContextBounds(this.#storage, id, context2);\n const entries = await activeEntries(this.#storage, id, bounds, context2);\n const docs = {};\n const incarnations = /* @__PURE__ */ new Map();\n for (const token of MOUNTED) {\n const loaded = await this.#session.conversationDocumentOnLine(token, id, context2);\n if (loaded === void 0)\n continue;\n docs[token.definition.kind] = loaded.value;\n incarnations.set(token.definition.kind, { id: loaded.record.id, version: loaded.version });\n }\n return { value: { conversation: conversation2, entries, docs }, docs: incarnations, observers: /* @__PURE__ */ new Set() };\n }\n };\n function advance(id, mount, publication, context2) {\n const docOps = [];\n const entryOps = [];\n let entries = mount.value.entries;\n for (const change of publication.changes) {\n if (change.type === \"entry\" && change.value.conversationId === id) {\n const entry = change.value;\n const value = entry;\n if (entry.head === void 0) {\n entryOps.push([\"p\", [\"entries\"], entries.length, 0, [value]]);\n entries = [...entries, entry];\n continue;\n }\n const target = entry.head;\n let kept = entries.findIndex((candidate) => candidate.head === void 0 && candidate.id >= target);\n if (kept < 0)\n kept = entries.length;\n entryOps.push([\"p\", [\"entries\"], 0, kept, [value]]);\n entries = [entry, ...entries.slice(kept)];\n continue;\n }\n if (change.type !== \"document\" || change.conversationId !== id)\n continue;\n const kind = change.record.kind;\n if (!MOUNTED_KINDS.has(kind) || change.record.key !== void 0)\n continue;\n const path = [\"docs\", kind];\n const mounted = mount.docs.get(kind);\n if (change.value === null) {\n if (mounted?.id !== change.record.id)\n continue;\n mount.docs.delete(kind);\n docOps.push([\"d\", path]);\n } else if (mounted?.id === change.record.id && mounted.version === change.version) {\n for (const op of change.ops)\n docOps.push(prefixed(op, path));\n } else {\n mount.docs.set(kind, { id: change.record.id, version: change.version });\n docOps.push([\"s\", path, change.value]);\n }\n }\n const before = mount.value;\n const ops = [...docOps, ...entryOps];\n const frameContext = withoutAbortSignal(context2);\n if (ops.length > 0) {\n const value = docOps.length === 0 ? mount.value : applyImmutable(mount.value, docOps);\n mount.value = entries === value.entries ? value : { ...value, entries };\n for (const observer of [...mount.observers])\n observer.advance?.(mount.value, ops, frameContext);\n }\n for (const observer of [...mount.observers]) {\n observer.publication?.(before, mount.value, ops, publication, frameContext);\n }\n }\n function prefixed(op, prefix) {\n const at = (path) => [...prefix, ...path];\n switch (op[0]) {\n case \"r\":\n return [\"s\", prefix, op[1]];\n case \"p\":\n return [\"p\", at(op[1]), op[2], op[3], op[4]];\n case \"m\":\n return [\"m\", at(op[1]), op[2]];\n case \"s\":\n return [\"s\", at(op[1]), op[2]];\n case \"d\":\n return [\"d\", at(op[1])];\n case \"a\":\n return [\"a\", at(op[1]), op[2]];\n case \"t\":\n return [\"t\", at(op[1]), op[2]];\n }\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/events.js\n function parts(view) {\n return {\n live: view.docs[\"pi.live\"] ?? {},\n inbox: view.docs[\"pi.inbox\"],\n agent: view.docs[\"pi.agent\"],\n usage: view.docs[\"pi.usage\"]\n };\n }\n function snapshotOf(view) {\n const { live, inbox, agent, usage: usage2 } = parts(view);\n return {\n type: \"snapshot\",\n entries: view.entries,\n ...live.run === void 0 ? {} : { run: { inputs: live.run.inputs } },\n ...live.generation === void 0 ? {} : { generation: live.generation },\n tools: live.tools ?? [],\n compactions: live.compactions ?? [],\n inbox: queued(inbox),\n agent: agent ?? AgentDoc.definition.initial(),\n usage: usage2 ?? UsageDoc.definition.initial()\n };\n }\n function queued(inbox) {\n return (inbox?.items ?? []).map((item) => ({ id: item.id, mode: item.mode }));\n }\n async function watchEvents(harness2, conversationId, context2) {\n let watch2;\n let snapshot;\n await conversationViews(harness2).attach(conversationId, async (initial, release, storage) => {\n const query = { conversationId, kind: \"pi.generation\", status: \"completing\" };\n const completing = await scanAll((cursor) => storage.scanTasks(query, 100, cursor, context2));\n const held = new Set(completing.map((record) => record.id));\n let current = initial;\n snapshot = snapshotOf(initial);\n watch2 = new CommittedWatch([], release, () => [snapshotOf(current)]);\n return {\n publication: (before, after, ops, publication, commitContext) => {\n current = after;\n const events = translate(conversationId, before, after, ops, publication, held);\n if (events.length > 0)\n watch2.advance(events, [], commitContext);\n },\n closeSession: () => watch2.closeSession()\n };\n }, context2);\n const signal = context2.abortSignal;\n if (signal?.aborted) {\n watch2.cancel();\n throw signal.reason;\n }\n if (signal !== void 0)\n watch2.observeCancellation(signal);\n return {\n snapshot,\n start: (listener) => watch2.start((events, _ops, deliveryContext) => listener(events, deliveryContext)),\n stop: () => watch2.stop(),\n closed: watch2.closed\n };\n }\n function resultOf(entries, callId) {\n return entries.find((entry) => {\n const message = entry.model?.[0];\n return message?.role === \"toolResult\" && message.toolCallId === callId;\n });\n }\n function translate(conversationId, before, after, viewOps, publication, held) {\n const entries = [];\n const tasks = /* @__PURE__ */ new Map();\n const submissions = [];\n for (const change of publication.changes) {\n if (change.type === \"entry\" && change.value.conversationId === conversationId)\n entries.push(change.value);\n if (change.type === \"task\" && change.value.conversationId === conversationId)\n tasks.set(change.value.id, change.value);\n if (change.type === \"submission\" && change.value.conversationId === conversationId) {\n submissions.push(change.value);\n }\n }\n if (viewOps.length === 0 && entries.length === 0 && tasks.size === 0 && submissions.length === 0)\n return [];\n submissions.sort((a, b) => a.id - b.id);\n const was = parts(before);\n const now = parts(after);\n const events = [];\n const slotsBefore = new Map((was.live.tools ?? []).map((slot) => [slot.callId, slot]));\n const slots = now.live.tools ?? [];\n for (const slot of slots) {\n if (slot.status !== \"running\" || slotsBefore.get(slot.callId)?.status === \"running\")\n continue;\n const checkpoint = slot.taskId === void 0 ? void 0 : tasks.get(slot.taskId)?.state.checkpoint;\n const args = checkpoint?.arguments ?? {};\n events.push({ type: \"tool_execution_start\", toolCallId: slot.callId, toolName: slot.name, args });\n }\n const partialBefore = was.live.generation?.message;\n const partial = now.live.generation?.message;\n if (partial !== void 0 && partialBefore === void 0)\n events.push({ type: \"message_start\", message: partial });\n else if (partial !== void 0 && partial !== partialBefore) {\n events.push({ type: \"message_update\", usage: partial.usage, changes: messageChanges(viewOps, partial) });\n }\n for (const [index3, slot] of slots.entries()) {\n const previous = slotsBefore.get(slot.callId);\n if (slot.status !== \"running\" || previous?.status !== \"running\")\n continue;\n const update = toolUpdate(viewOps, index3, slot, previous);\n if (update === void 0)\n continue;\n events.push({ type: \"tool_execution_update\", toolCallId: slot.callId, toolName: slot.name, ...update });\n }\n const generation = now.live.generation;\n const generationBefore = was.live.generation;\n if (generation?.retry !== void 0 && generationBefore?.retry === void 0) {\n const { at, error } = generation.retry;\n events.push({ type: \"auto_retry_start\", attempt: generation.attempt, at, errorMessage: error });\n }\n if (generationBefore?.retry !== void 0 && generation?.retry === void 0) {\n events.push({ type: \"auto_retry_end\", attempt: generationBefore.attempt });\n }\n if (generation?.deferred !== void 0 && generation.deferred.pollAt !== generationBefore?.deferred?.pollAt) {\n events.push({ type: \"deferred_poll\", pollAt: generation.deferred.pollAt });\n }\n const toolEnds = [];\n const endTool = (callId, name, entryId) => {\n const entry = entries.find((candidate) => candidate.id === entryId);\n toolEnds.push({\n type: \"tool_execution_end\",\n toolCallId: callId,\n toolName: name,\n ...entry === void 0 ? {} : { entry }\n });\n };\n for (const previous of slotsBefore.values()) {\n if (previous.status === \"done\")\n continue;\n const slot = slots.find((candidate) => candidate.callId === previous.callId);\n if (slot?.status === \"done\")\n endTool(previous.callId, previous.name, slot.entry);\n else if (slot === void 0)\n endTool(previous.callId, previous.name, resultOf(entries, previous.callId)?.id);\n }\n for (const slot of slots) {\n if (slot.status === \"done\" && !slotsBefore.has(slot.callId))\n endTool(slot.callId, slot.name, slot.entry);\n }\n let assistantAppended = false;\n for (const entry of entries) {\n events.push(...toolEnds.filter((end) => end.entry === entry));\n const message = entry.model?.[0];\n if (message === void 0) {\n events.push({ type: \"entry_appended\", entry });\n continue;\n }\n const streamed = message.role === \"assistant\" && partialBefore !== void 0 && !assistantAppended;\n if (message.role === \"assistant\")\n assistantAppended = true;\n if (!streamed)\n events.push({ type: \"message_start\", message });\n events.push({ type: \"message_end\", entry });\n }\n events.push(...toolEnds.filter((end) => end.entry === void 0));\n const compactionsBefore = was.live.compactions ?? [];\n const compactions = now.live.compactions ?? [];\n for (const { taskId, reason } of compactionsBefore) {\n if (!compactions.some((status) => status.taskId === taskId)) {\n events.push({ type: \"compaction_end\", taskId, reason });\n }\n }\n let turnEnded = false;\n for (const task of tasks.values()) {\n const status = task.state.status;\n if (task.kind === \"pi.generation\" && status === \"completing\" && !held.has(task.id)) {\n held.add(task.id);\n turnEnded = true;\n }\n if (status !== \"terminal\")\n continue;\n if (task.kind === \"pi.generation\" && !held.delete(task.id))\n turnEnded = true;\n const outcome = task.state.outcome;\n if (outcome.status === \"faulted\" || outcome.status === \"orphaned\") {\n const message = outcome.status === \"faulted\" ? outcome.error.message : outcome.reason;\n events.push({ type: \"task_failed\", taskId: task.id, kind: task.kind, message });\n }\n }\n if (turnEnded)\n events.push({ type: \"turn_end\" });\n const run2 = now.live.run;\n const runBefore = was.live.run;\n const runChanged = run2?.inputs[0] !== runBefore?.inputs[0];\n if (runBefore !== void 0 && runChanged)\n events.push({ type: \"run_end\", inputs: runBefore.inputs });\n for (const record of submissions)\n events.push({ type: \"submission\", record });\n if (now.inbox !== was.inbox)\n events.push({ type: \"inbox_update\", items: queued(now.inbox) });\n if (now.agent !== was.agent) {\n events.push({ type: \"agent_changed\", agent: now.agent ?? AgentDoc.definition.initial() });\n }\n if (now.usage !== was.usage)\n events.push({ type: \"usage_changed\", usage: now.usage ?? UsageDoc.definition.initial() });\n for (const { taskId, reason, blocking } of compactions) {\n if (!compactionsBefore.some((status) => status.taskId === taskId)) {\n events.push({ type: \"compaction_start\", taskId, reason, blocking });\n }\n }\n if (run2 !== void 0 && runChanged)\n events.push({ type: \"run_start\", inputs: run2.inputs });\n if (run2 !== void 0 && run2.taskId !== runBefore?.taskId && tasks.get(run2.taskId)?.kind === \"pi.generation\") {\n events.push({ type: \"turn_start\" });\n }\n return events;\n }\n var PARTIAL_PATH = [\"docs\", \"pi.live\", \"generation\", \"message\"];\n function messageChanges(viewOps, message) {\n const changes = [];\n const whole = /* @__PURE__ */ new Set();\n for (const op of viewOps) {\n const path = op[1];\n if (!startsWith(path, PARTIAL_PATH)) {\n if (startsWith(PARTIAL_PATH, path))\n return [{ type: \"message\", message }];\n continue;\n }\n const rest = path.slice(PARTIAL_PATH.length);\n if (rest[0] === \"usage\")\n continue;\n if (rest[0] !== \"content\")\n return [{ type: \"message\", message }];\n if (rest.length === 1) {\n if (op[0] !== \"p\" || op[3] !== 0)\n return [{ type: \"message\", message }];\n for (const [offset, block] of op[4].entries()) {\n const type = block.type === \"text\" ? \"text_start\" : block.type === \"thinking\" ? \"thinking_start\" : \"toolcall_start\";\n changes.push({ type, contentIndex: op[2] + offset, block });\n }\n continue;\n }\n const contentIndex = rest[1];\n const field = rest[2];\n if (whole.has(contentIndex))\n continue;\n if (op[0] === \"a\" && rest.length === 3 && (field === \"text\" || field === \"thinking\")) {\n changes.push({ type: field === \"text\" ? \"text_delta\" : \"thinking_delta\", contentIndex, delta: op[2] });\n } else if (op[0] === \"a\" && field === \"arguments\") {\n changes.push({ type: \"toolcall_delta\", contentIndex, path: rest.slice(3), delta: op[2] });\n } else {\n whole.add(contentIndex);\n changes.push({ type: \"block\", contentIndex, block: message.content[contentIndex] });\n }\n }\n return changes;\n }\n function toolUpdate(viewOps, index3, slot, previous) {\n const outputPath = [\"docs\", \"pi.live\", \"tools\", index3, \"output\"];\n let trimStart = 0;\n let append = \"\";\n let set = false;\n for (const op of viewOps) {\n if (!startsWith(op[1], outputPath))\n continue;\n if (op[0] === \"t\")\n trimStart += op[2];\n else if (op[0] === \"a\")\n append += op[2];\n else\n set = true;\n }\n let output;\n if (set || slot.output !== previous.output && trimStart === 0 && append === \"\")\n output = { set: slot.output ?? \"\" };\n else if (trimStart > 0 || append !== \"\") {\n output = { ...trimStart > 0 ? { trimStart } : {}, ...append === \"\" ? {} : { append } };\n }\n const update = {\n ...output === void 0 ? {} : { output },\n ...slot.details === previous.details ? {} : { details: slot.details ?? null },\n ...slot.diagnostics === previous.diagnostics ? {} : { diagnostics: slot.diagnostics ?? [] }\n };\n return Object.keys(update).length === 0 ? void 0 : update;\n }\n function startsWith(path, prefix) {\n return prefix.length <= path.length && prefix.every((segment, index3) => path[index3] === segment);\n }\n\n // node_modules/@earendil-works/pi-durable/dist/types.js\n var ROOT_CONVERSATION_ID = 1;\n\n // node_modules/@earendil-works/pi-durable/dist/session/forks.js\n var SCAN_PAGE_SIZE2 = 256;\n async function prepareForkDocumentCopies(storage, parentConversationId, at, childConversationId, context2) {\n const entry = await storage.entry(parentConversationId, at, context2);\n if (entry === void 0)\n throw new Error(`Entry ${at} is not visible from conversation ${parentConversationId}`);\n const copies = [];\n const copiedAddresses = /* @__PURE__ */ new Set();\n await collectCopies(storage, { kind: \"conversation\", conversationId: entry.entry.conversationId }, entry.commitSeq, \"asOf\", childConversationId, copies, copiedAddresses, context2);\n await collectCopies(storage, { kind: \"conversation\", conversationId: parentConversationId }, \"current\", \"current\", childConversationId, copies, copiedAddresses, context2);\n return copies;\n }\n async function collectCopies(storage, scope, at, policy, childConversationId, copies, copiedAddresses, context2) {\n let cursor;\n do {\n const page2 = await storage.scanDocuments({ scope, at }, SCAN_PAGE_SIZE2, cursor, context2);\n for (const source of page2.items) {\n if (source.scope.kind !== \"conversation\" || source.fork !== policy)\n continue;\n const id = await storage.mintId();\n const identity = {\n id,\n kind: source.kind,\n ...source.key === void 0 ? {} : { key: source.key },\n scope: { kind: \"conversation\", conversationId: childConversationId }\n };\n const record = source.history === \"latest\" ? { ...identity, history: \"latest\", fork: source.fork } : { ...identity, history: \"rewindable\", fork: source.fork };\n const copyAddress = addressId(record);\n if (copiedAddresses.has(copyAddress)) {\n const member = record.key === void 0 ? record.kind : `${record.kind}/${record.key}`;\n throw new Error(`Fork selects multiple source documents for ${member}`);\n }\n copiedAddresses.add(copyAddress);\n copies.push({ record, source: { id: source.id, at } });\n }\n cursor = page2.next;\n } while (cursor !== void 0);\n }\n\n // node_modules/@earendil-works/pi-durable/dist/session/transaction.js\n function applySubmissionChange(current, change) {\n if (current.status === \"done\" || current.status === \"unanswered\")\n return current;\n if (change.status === \"placed\") {\n if (current.status !== \"queued\")\n throw new Error(`Submission ${current.id} is not queued`);\n const status = current.type === \"input\" ? \"placed\" : \"done\";\n return { ...current, status, entry: change.entry };\n }\n if (change.status === \"done\" && current.status !== \"placed\") {\n throw new Error(`Submission ${current.id} is not a placed input`);\n }\n return { ...current, ...change };\n }\n var INTERNAL_SCAN_PAGE_SIZE = 256;\n var EMPTY_OPERATIONS = [];\n var TABLE_JSON_COPY_OPTIONS = { omitUndefinedProperties: true };\n var Transaction = class {\n #host;\n #context;\n #scope;\n #pendingOperations = /* @__PURE__ */ new Set();\n #sealed = false;\n #hasTableWrite = false;\n /** Atomic batch; conversation and entry writes stage eagerly, while task and document writes assemble later. */\n #writes = [];\n #createdConversationIds = /* @__PURE__ */ new Set();\n #forkSourceConversationIds = /* @__PURE__ */ new Set();\n #forkSourceDocumentIds = /* @__PURE__ */ new Set();\n /** One entry per task touched by a public read, candidate write, or document-owner lookup. */\n #tasksById = /* @__PURE__ */ new Map();\n /** Submissions created by this transaction, by ID. */\n #submissions = /* @__PURE__ */ new Map();\n /** Submission settlements and placements in staging order; resolved against the latest candidate record during assembly. */\n #submissionChanges = [];\n /** Write and publication plans of every staged incarnation, built during assembly. */\n #plans = [];\n /** Every document acquisition or retirement marker in staging order. */\n #documents = [];\n /** Latest transaction-local incarnation or retirement marker at each logical address. */\n #latestDocumentByAddress = /* @__PURE__ */ new Map();\n constructor(host, context2, scope = {}) {\n this.#host = host;\n this.#context = context2;\n this.#scope = scope;\n }\n // ─── Table reads ────────────────────────────────────────────────────────\n conversation(id) {\n return this.#read(\"conversation\", () => this.#host.storage.conversation(id, this.#context));\n }\n entry(first, second) {\n const kind = typeof first === \"number\" ? void 0 : first.kind;\n const id = typeof first === \"number\" ? first : second;\n return this.#read(\"entry\", async () => {\n const entry = (await this.#host.storage.entry(id, this.#context))?.entry;\n return kind === void 0 || entry?.kind === kind ? entry : void 0;\n });\n }\n task(id) {\n return this.#read(\"task\", () => this.#committedTask(id));\n }\n scanConversations(query, limit, cursor) {\n return this.#read(\"scanConversations\", () => this.#host.storage.scanConversations(query, limit, cursor, this.#context));\n }\n scanEntries(query, limit, cursor) {\n return this.#read(\"scanEntries\", () => this.#host.storage.scanEntries(query, limit, cursor, this.#context));\n }\n latestHeadMarker(conversationId) {\n return this.#read(\"latestHeadMarker\", () => this.#host.storage.findLatestHeadMarker(conversationId, void 0, this.#context));\n }\n scanTasks(query, limit, cursor) {\n return this.#read(\"scanTasks\", () => this.#host.storage.scanTasks(query, limit, cursor, this.#context));\n }\n /** Internal: committed submission record. */\n submission(id) {\n return this.#read(\"submission\", () => this.#host.storage.submission(id, this.#context));\n }\n /** Committed submission with a conversation-scoped request ID. */\n submissionByRequest(conversationId, requestId) {\n return this.#read(\"submissionByRequest\", () => this.#host.storage.submissionByRequest(conversationId, requestId, this.#context));\n }\n // ─── Table writes ───────────────────────────────────────────────────────\n createConversation(options) {\n return this.#write(() => this.#stageConversation(void 0, options.ownership));\n }\n /** Internal final-form bootstrap path for the reserved root identity. */\n createRootConversation() {\n return this.#write(() => this.#stageConversation(void 0, { kind: \"ownerless\" }, ROOT_CONVERSATION_ID));\n }\n forkConversation(parentConversationId, at, options) {\n return this.#write(() => this.#stageConversation({ conversationId: parentConversationId, at }, options.ownership));\n }\n async #stageConversation(parent, ownership, reservedId) {\n const ownerTaskId = ownership.kind === \"task\" ? ownership.taskId : void 0;\n const id = reservedId ?? await this.#host.storage.mintId();\n this.#assertOpen();\n let owner;\n if (ownerTaskId !== void 0) {\n const task = await this.#currentTask(ownerTaskId);\n this.#assertOpen();\n if (task === void 0)\n throw new Error(`Conversation owner task ${ownerTaskId} does not exist`);\n owner = { conversationId: task.conversationId, taskId: ownerTaskId };\n }\n const record = {\n id,\n ...parent === void 0 ? {} : { parent },\n ...owner === void 0 ? {} : { owner }\n };\n const copies = parent === void 0 ? [] : await prepareForkDocumentCopies(this.#host.storage, parent.conversationId, parent.at, id, this.#context);\n this.#assertOpen();\n for (const copy2 of copies) {\n this.#forkSourceDocumentIds.add(copy2.source.id);\n const entry = {\n addressId: addressId(copy2.record),\n address: copy2.record,\n target: { kind: \"fork-copy\", ...copy2 },\n retireOnCommit: false\n };\n this.#documents.push(entry);\n this.#latestDocumentByAddress.set(entry.addressId, entry);\n }\n if (parent !== void 0)\n this.#forkSourceConversationIds.add(parent.conversationId);\n this.#createdConversationIds.add(id);\n this.#writes.push({ type: \"conversation\", value: record });\n await this.#host.conversationCreated(this, record);\n this.#assertOpen();\n return record;\n }\n appendEntry(first, second, third) {\n if (typeof first === \"number\")\n return this.#appendEntry(first, second);\n return this.#appendEntry(second, { ...third, kind: first.kind });\n }\n #appendEntry(conversationId, value) {\n return this.#write(async () => {\n await this.#requireConversation(conversationId);\n this.#assertOpen();\n const id = await this.#host.storage.mintId();\n this.#assertOpen();\n const { head, ...rest } = value;\n const record = copyJson({\n ...rest,\n id,\n conversationId,\n head: head === \"self\" ? id : head,\n byTaskId: this.#scope.taskId\n }, TABLE_JSON_COPY_OPTIONS);\n this.#writes.push({ type: \"entry\", value: record });\n return record;\n });\n }\n createTask(task, input, options) {\n return this.#write(async () => {\n const ownership = options.ownership;\n let owner;\n if (ownership.kind === \"task\") {\n owner = await this.#currentTask(ownership.taskId);\n this.#assertOpen();\n if (owner === void 0)\n throw new Error(`Task owner ${ownership.taskId} does not exist`);\n if (options.background === true)\n throw new TypeError(\"A child task cannot be background\");\n if (options.conversationId !== void 0 && options.conversationId !== owner.conversationId) {\n throw new Error(`A child task lives in its owner's conversation ${owner.conversationId}`);\n }\n }\n const conversationId = owner?.conversationId ?? options.conversationId ?? this.#scope.conversationId;\n if (conversationId === void 0)\n throw new TypeError(\"Tx.createTask() requires options.conversationId\");\n await this.#requireConversation(conversationId);\n this.#assertOpen();\n const definition = task.definition;\n const checkpoint = definition.initial(input);\n const id = await this.#host.storage.mintId();\n this.#assertOpen();\n const record = copyJson({\n id,\n conversationId,\n kind: definition.name,\n version: definition.version,\n input,\n ...owner === void 0 ? {} : { owner: owner.id },\n background: options.background ?? false,\n abortRequested: false,\n state: { status: \"pending\", checkpoint }\n }, TABLE_JSON_COPY_OPTIONS);\n this.#tasksById.set(id, { write: { kind: \"create\", record } });\n return id;\n });\n }\n /** Create a raw submission record with a fresh ID; no admission rules apply. */\n createSubmission(create) {\n return this.#write(async () => {\n await this.#requireConversation(create.conversationId);\n this.#assertOpen();\n const id = await this.#host.storage.mintId();\n this.#assertOpen();\n const record = copyJson({ ...create, id }, TABLE_JSON_COPY_OPTIONS);\n this.#submissions.set(id, record);\n return record;\n });\n }\n /**\n * Settle a submission. Resolved during assembly against the transaction's latest candidate record, falling back to\n * committed state, so it is not a caller table read and works after the first table write.\n */\n settleSubmission(id, settlement) {\n this.#assertOpen();\n this.#hasTableWrite = true;\n this.#submissionChanges.push({ id, change: copyJson(settlement) });\n }\n /** Place a queued submission at `entry`; resolved during assembly like `settleSubmission()`. */\n placeSubmission(id, entry) {\n this.#assertOpen();\n this.#hasTableWrite = true;\n this.#submissionChanges.push({ id, change: { status: \"placed\", entry } });\n }\n /** Internal: replace one task record completely. Tasks change their own state through their runtime. */\n setTask(value) {\n this.#assertOpen();\n this.#hasTableWrite = true;\n const task = this.#taskEntry(value.id);\n const candidate = task.write?.record;\n if (candidate?.state.status === \"terminal\") {\n throw new Error(`Task ${value.id} already has a terminal candidate`);\n }\n if (candidate !== void 0 && candidate.conversationId !== value.conversationId) {\n throw new Error(`Task ${value.id} cannot change conversations`);\n }\n task.write = {\n kind: task.write?.kind === \"create\" ? \"create\" : \"replace\",\n record: copyJson(this.#stampTimes(value, candidate), TABLE_JSON_COPY_OPTIONS)\n };\n }\n /** Internal: candidate records of the tasks this transaction created or replaced so far. */\n stagedTasks() {\n const records = [];\n for (const task of this.#tasksById.values())\n if (task.write !== void 0)\n records.push(task.write.record);\n return records;\n }\n /** Internal: conversations this transaction created or forked so far. */\n stagedConversations() {\n const records = [];\n for (const write of this.#writes)\n if (write.type === \"conversation\")\n records.push(write.value);\n return records;\n }\n doc(token, ...args) {\n try {\n this.#assertOpen();\n const definition = token.definition;\n const resolved = resolveAddress(definition, args);\n this.#assertTaskDocumentsOpen(resolved);\n const latest = this.#latestDocumentByAddress.get(resolved.id);\n if (latest !== void 0 && !latest.retireOnCommit) {\n if (latest.draftPromise !== void 0)\n return latest.draftPromise;\n if (latest.target?.kind === \"fork-copy\") {\n latest.draftPromise = this.#track(this.#acquireForkCopy(latest, definition, latest.target));\n return latest.draftPromise;\n }\n }\n const seed = definition.family === true ? copyJson(args[resolved.nextArgument]) : void 0;\n const docEntry = {\n addressId: resolved.id,\n address: resolved.address,\n definition,\n retireOnCommit: false\n };\n this.#documents.push(docEntry);\n this.#latestDocumentByAddress.set(docEntry.addressId, docEntry);\n docEntry.draftPromise = this.#track(this.#acquire(docEntry, seed, latest?.retireOnCommit === true));\n return docEntry.draftPromise;\n } catch (error) {\n return Promise.reject(error);\n }\n }\n retireDoc(token, ...args) {\n try {\n this.#assertOpen();\n const definition = token.definition;\n const resolved = resolveAddress(definition, args);\n const latest = this.#latestDocumentByAddress.get(resolved.id);\n if (latest?.retireOnCommit)\n return Promise.resolve();\n if (latest?.target?.kind === \"fork-copy\") {\n checkRecordScope(definition, latest.target.record);\n latest.retireOnCommit = true;\n return Promise.resolve();\n }\n if (latest?.draftPromise !== void 0) {\n latest.retireOnCommit = true;\n return this.#track(latest.draftPromise.then(() => void 0));\n }\n const entry = {\n addressId: resolved.id,\n address: resolved.address,\n definition,\n retireOnCommit: true\n };\n this.#documents.push(entry);\n this.#latestDocumentByAddress.set(entry.addressId, entry);\n return this.#track(this.#findRetirement(entry));\n } catch (error) {\n return Promise.reject(error);\n }\n }\n async #acquire(entry, seed, skipLoad) {\n const definition = entry.definition;\n const loaded = skipLoad ? void 0 : await this.#host.load(definition, entry.addressId, entry.address, this.#context);\n this.#assertOpen();\n if (loaded !== void 0) {\n checkRecordScope(definition, loaded.record);\n checkRecordVersion(definition, loaded.record, loaded.storedVersion);\n entry.target = { kind: \"loaded\", document: loaded };\n entry.change = loaded.tracker.beginChange();\n return entry.change.state;\n }\n const scope = entry.address.scope;\n if (scope.kind === \"conversation\")\n await this.#requireConversation(scope.conversationId);\n if (scope.kind === \"task\") {\n const task = await this.#currentTask(scope.taskId);\n if (task === void 0)\n throw new Error(`Task ${scope.taskId} does not exist`);\n if (task.state.status === \"terminal\")\n throw new Error(`Task ${scope.taskId} is terminal`);\n }\n this.#assertOpen();\n const value = copyJson(definition.family === true ? definition.initial(seed) : definition.initial());\n const id = await this.#host.storage.mintId();\n this.#assertOpen();\n const tracker = track(value);\n entry.target = {\n kind: \"created\",\n record: documentCreate(definition, entry.address, id),\n version: definition.version,\n tracker\n };\n entry.change = tracker.beginChange();\n return entry.change.state;\n }\n async #acquireForkCopy(entry, definition, target) {\n const stored = await this.#host.storage.document(target.source.id, target.source.at, this.#context);\n this.#assertOpen();\n if (stored === void 0) {\n throw new Error(`Fork source document ${target.source.id} cannot be read`);\n }\n if (stored.record.scope.kind !== \"conversation\" || stored.record.kind !== target.record.kind || stored.record.key !== target.record.key || stored.record.history !== target.record.history || stored.record.fork !== target.record.fork) {\n throw new Error(`Fork source document ${target.source.id} does not match the copied record`);\n }\n const value = materializeDocumentValue(definition, target.record, stored.version, stored.value);\n const tracker = track(value);\n entry.definition = definition;\n entry.target = { kind: \"created\", record: target.record, version: definition.version, tracker };\n entry.change = tracker.beginChange();\n return entry.change.state;\n }\n async #findRetirement(entry) {\n const record = this.#host.cached(entry.addressId)?.record ?? await this.#host.storage.findDocument(entry.address, \"current\", this.#context);\n this.#assertOpen();\n if (record === void 0)\n return;\n checkRecordScope(entry.definition, record);\n entry.target = { kind: \"retire-only\", record };\n }\n // ─── Settlement ─────────────────────────────────────────────────────────\n /** Seal after callback failure: abort every change and observe every pending operation. */\n async settleFailure() {\n this.#sealed = true;\n this.#abortChanges();\n await Promise.allSettled(this.#pendingOperations);\n }\n /**\n * Seal after callback success, prepare every open change, and assemble the atomic batch.\n * Any failure aborts every change before Storage admission.\n */\n async settleSuccess() {\n this.#sealed = true;\n if (this.#pendingOperations.size > 0) {\n this.#abortChanges();\n await Promise.allSettled(this.#pendingOperations);\n throw new Error(\"Session commit callback settled before its pending Tx operations\");\n }\n try {\n for (const document of this.#documents) {\n if (document.change !== void 0)\n document.prepared = document.change.prepare();\n }\n return await this.#assemble();\n } catch (error) {\n this.#abortChanges();\n throw error;\n }\n }\n /** Abort every prepared change after Storage failure or when no write is required. */\n discard() {\n this.#abortChanges();\n }\n /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */\n adopt(seq) {\n const publications = [];\n for (const plan of this.#plans) {\n const committed = \"createdAt\" in plan.record;\n let record = committed ? plan.record : { ...plan.record, createdAt: seq };\n if (plan.retire)\n record = { ...record, retiredAt: seq };\n const change = plan.change;\n if (change !== void 0) {\n const { tracker, prepared, loaded, version } = change;\n if (loaded === void 0 ? !plan.retire : prepared.ops.length > 0)\n tracker.adopt(prepared);\n else\n prepared.abort();\n if (loaded !== void 0) {\n if (loaded.storedVersion < version)\n loaded.storedVersion = version;\n if (plan.content?.type === \"document.change\") {\n if (plan.content.content.kind === \"base\")\n loaded.deltasSinceBase = 0;\n else\n loaded.deltasSinceBase++;\n }\n } else if (!plan.retire) {\n this.#host.install({\n addressId: plan.addressId,\n record,\n storedVersion: version,\n valueVersion: version,\n deltasSinceBase: 0,\n tracker\n });\n }\n }\n const conversationId = plan.conversationId;\n if (plan.retire) {\n if (committed)\n this.#host.evict(plan.addressId, record.id);\n const retired = { version: void 0, value: null, ops: EMPTY_OPERATIONS };\n publications.push({ type: \"document\", record, conversationId, ...retired });\n } else if (plan.content?.type === \"document.copy\") {\n publications.push({\n type: \"document.copy\",\n record,\n conversationId,\n source: plan.content.source\n });\n } else if (change !== void 0 && publishes(plan)) {\n const ops = change.loaded === void 0 ? EMPTY_OPERATIONS : change.prepared.ops;\n publications.push({\n type: \"document\",\n record,\n conversationId,\n version: change.version,\n value: change.prepared.value,\n ops\n });\n }\n }\n return publications;\n }\n async #assemble() {\n const storage = this.#host.storage;\n const plans = this.#plans;\n for (const document of this.#documents) {\n const plan = planDocument(document);\n if (plan !== void 0)\n plans.push(plan);\n }\n this.#rejectForkSourceWrites(plans);\n await this.#validateOwners();\n for (const [id, task] of this.#tasksById) {\n if (task.write?.kind !== \"replace\")\n continue;\n const committed = await this.#committedTask(id);\n if (committed === void 0)\n throw new Error(`Task ${id} does not exist`);\n if (committed.state.status === \"terminal\")\n throw new Error(`Task ${id} is already terminal`);\n if (committed.conversationId !== task.write.record.conversationId) {\n throw new Error(`Task ${id} cannot change conversations`);\n }\n }\n const terminalTaskIds = /* @__PURE__ */ new Set();\n for (const task of this.#tasksById.values()) {\n if (task.write?.record.state.status === \"terminal\")\n terminalTaskIds.add(task.write.record.id);\n }\n if (terminalTaskIds.size > 0) {\n const retiring = /* @__PURE__ */ new Set();\n for (const plan of plans) {\n const scope = plan.record.scope;\n if (scope.kind !== \"task\" || !terminalTaskIds.has(scope.taskId))\n continue;\n plan.retire = true;\n retiring.add(plan.record.id);\n }\n for (const taskId of terminalTaskIds) {\n if (this.#tasksById.get(taskId)?.write?.kind === \"create\")\n continue;\n let cursor;\n do {\n const page2 = await storage.scanDocuments({ scope: { kind: \"task\", taskId }, at: \"current\" }, INTERNAL_SCAN_PAGE_SIZE, cursor, this.#context);\n for (const record of page2.items) {\n if (retiring.has(record.id))\n continue;\n plans.push({ addressId: addressId(record), record, retire: true });\n retiring.add(record.id);\n }\n cursor = page2.next;\n } while (cursor !== void 0);\n }\n }\n for (const plan of plans) {\n if (!publishes(plan))\n continue;\n const scope = plan.record.scope;\n if (scope.kind === \"conversation\")\n plan.conversationId = scope.conversationId;\n if (scope.kind !== \"task\")\n continue;\n const task = this.#taskEntry(scope.taskId);\n if (task.publicationConversationId === void 0) {\n const current = await this.#currentTask(scope.taskId);\n if (current !== void 0)\n task.publicationConversationId = current.conversationId;\n }\n plan.conversationId = task.publicationConversationId;\n }\n for (const { id, change } of this.#submissionChanges) {\n const current = this.#submissions.get(id) ?? await storage.submission(id, this.#context);\n if (current === void 0)\n throw new Error(`Submission ${id} does not exist`);\n const next = applySubmissionChange(current, change);\n if (next !== current)\n this.#submissions.set(id, next);\n }\n const writes = this.#writes;\n for (const value of this.#submissions.values())\n writes.push({ type: \"submission\", value });\n for (const task of this.#tasksById.values()) {\n if (task.write !== void 0)\n writes.push({ type: \"task\", value: task.write.record });\n }\n for (const plan of plans) {\n const change = plan.change;\n if (plan.content?.type === \"document.change\" && plan.content.content.kind === \"delta\" && change?.loaded) {\n const { prepared, version } = change;\n const info = { deltasSinceBase: change.loaded.deltasSinceBase };\n if (change.definition?.checkpointWhen?.(prepared.value, prepared.ops, info)) {\n plan.content = { ...plan.content, content: { version, kind: \"base\", value: prepared.value } };\n }\n }\n if (plan.content !== void 0)\n writes.push(plan.content);\n if (plan.retire)\n writes.push({ type: \"document.retire\", id: plan.record.id });\n }\n return writes;\n }\n // ─── Helpers ────────────────────────────────────────────────────────────\n /**\n * New owned work needs a live owner, judged on the owner's final candidate: not `completing`, terminal, or\n * abort-marked. A task therefore cannot create owned work in the commit that finishes it (spec §5.5).\n */\n async #validateOwners() {\n const owners = [];\n for (const write of this.#writes) {\n if (write.type !== \"conversation\" || write.value.owner === void 0)\n continue;\n owners.push({ what: \"Conversation owner task\", taskId: write.value.owner.taskId });\n }\n for (const task of this.#tasksById.values()) {\n const record = task.write?.kind === \"create\" ? task.write.record : void 0;\n if (record?.owner !== void 0)\n owners.push({ what: \"Task owner\", taskId: record.owner });\n }\n for (const { what, taskId } of owners) {\n const task = await this.#currentTask(taskId);\n if (task === void 0)\n throw new Error(`${what} ${taskId} does not exist`);\n if (task.state.status === \"terminal\" || task.state.status === \"completing\") {\n throw new Error(`${what} ${taskId} is ${task.state.status}`);\n }\n if (task.abortRequested)\n throw new Error(`${what} ${taskId} is abort-marked`);\n }\n }\n #rejectForkSourceWrites(plans) {\n for (const plan of plans) {\n if (plan.content === void 0 && !plan.retire)\n continue;\n const record = plan.record;\n if (this.#forkSourceDocumentIds.has(record.id)) {\n throw new Error(`Cannot change fork source document ${record.id} in the fork transaction`);\n }\n const scope = plan.record.scope;\n if (scope.kind === \"conversation\" && this.#forkSourceConversationIds.has(scope.conversationId) && record.scope.kind === \"conversation\" && record.fork === \"current\") {\n throw new Error(`Cannot fork conversation ${scope.conversationId} while changing its current-policy documents`);\n }\n }\n }\n #abortChanges() {\n for (const document of this.#documents)\n document.change?.abort();\n }\n #assertOpen() {\n if (this.#sealed)\n throw new Error(\"Transaction has settled\");\n }\n #assertTaskDocumentsOpen(resolved) {\n const scope = resolved.address.scope;\n if (scope.kind === \"task\" && this.#tasksById.get(scope.taskId)?.write?.record.state.status === \"terminal\") {\n throw new Error(`Task ${scope.taskId} is terminal`);\n }\n }\n /** Register an operation so callback settlement can reject and drain it. */\n #track(operation) {\n this.#pendingOperations.add(operation);\n const settle3 = () => {\n this.#pendingOperations.delete(operation);\n };\n operation.then(settle3, settle3);\n return operation;\n }\n #read(method, read2) {\n try {\n this.#assertOpen();\n if (this.#hasTableWrite)\n throw new ReadAfterWrite(method);\n return this.#track(read2());\n } catch (error) {\n return Promise.reject(error);\n }\n }\n #write(write) {\n try {\n this.#assertOpen();\n this.#hasTableWrite = true;\n return this.#track(write());\n } catch (error) {\n return Promise.reject(error);\n }\n }\n async #requireConversation(id) {\n if (this.#createdConversationIds.has(id))\n return;\n if (await this.#host.storage.conversation(id, this.#context) === void 0) {\n throw new Error(`Conversation ${id} does not exist`);\n }\n }\n /**\n * Lifecycle times: `startedAt` on the first change to `running`, `endedAt` on the change to `terminal`. Once set,\n * they carry over from the replaced record; records written before they existed lack them.\n */\n #stampTimes(value, candidate) {\n const status = value.state.status;\n const now = (stamps) => stamps ? this.#host.now() : void 0;\n const startedAt = candidate?.startedAt ?? value.startedAt ?? now(status === \"running\");\n const endedAt = candidate?.endedAt ?? value.endedAt ?? now(status === \"terminal\");\n if (startedAt === value.startedAt && endedAt === value.endedAt)\n return value;\n return {\n ...value,\n ...startedAt === void 0 ? {} : { startedAt },\n ...endedAt === void 0 ? {} : { endedAt }\n };\n }\n #taskEntry(id) {\n let task = this.#tasksById.get(id);\n if (task === void 0) {\n task = {};\n this.#tasksById.set(id, task);\n }\n return task;\n }\n /** Latest candidate task record, falling back to committed state; not a caller table read. */\n async #currentTask(id) {\n return this.#tasksById.get(id)?.write?.record ?? await this.#committedTask(id);\n }\n #committedTask(id) {\n const task = this.#taskEntry(id);\n task.committedRead ??= this.#host.storage.task(id, this.#context);\n return task.committedRead;\n }\n };\n function planDocument(document) {\n const target = document.target;\n if (target === void 0)\n return void 0;\n const plan = { addressId: document.addressId, retire: document.retireOnCommit };\n switch (target.kind) {\n case \"created\": {\n const prepared = document.prepared;\n const { record, version, tracker } = target;\n const content = { version, kind: \"base\", value: prepared.value };\n return {\n ...plan,\n record,\n content: { type: \"document.create\", record, content },\n change: { tracker, prepared, version }\n };\n }\n case \"fork-copy\":\n return {\n ...plan,\n record: target.record,\n content: { type: \"document.copy\", record: target.record, source: target.source }\n };\n case \"retire-only\":\n return { ...plan, record: target.record };\n case \"loaded\": {\n const loaded = target.document;\n const definition = document.definition;\n const prepared = document.prepared;\n const version = definition.version;\n const id = loaded.record.id;\n const content = loaded.storedVersion < version ? { type: \"document.change\", id, content: { version, kind: \"base\", value: prepared.value } } : prepared.ops.length > 0 ? { type: \"document.change\", id, content: { version, kind: \"delta\", ops: prepared.ops } } : void 0;\n const change = {\n tracker: loaded.tracker,\n prepared,\n version,\n loaded,\n definition\n };\n return { ...plan, record: loaded.record, change, ...content === void 0 ? {} : { content } };\n }\n }\n }\n function publishes(plan) {\n return plan.retire || plan.change?.loaded === void 0 || plan.content !== void 0;\n }\n\n // node_modules/@earendil-works/pi-durable/dist/session/session.js\n function createSession(storage, options) {\n return new SessionImpl(storage, options?.now);\n }\n var SessionImpl = class {\n #storage;\n #documents = /* @__PURE__ */ new Map();\n #commitListeners = /* @__PURE__ */ new Set();\n #closeListeners = /* @__PURE__ */ new Set();\n #host;\n #tail = Promise.resolve();\n #closing;\n #poison;\n constructor(storage, now = Date.now) {\n this.#storage = storage;\n this.#host = {\n storage,\n now,\n cached: (id) => this.#documents.get(id),\n load: (definition, addressId2, address, context2) => this.#loadDocument(definition, addressId2, address, context2),\n install: (document) => {\n this.#documents.set(document.addressId, document);\n },\n evict: (id, recordId) => {\n if (this.#documents.get(id)?.record.id === recordId)\n this.#documents.delete(id);\n },\n conversationCreated: (tx, record) => this.conversationCreated(tx, record)\n };\n }\n commit(change, context2) {\n return this.commitWith(change, context2);\n }\n /**\n * Internal commit exposing the concrete transaction and its internal operations, such as the reserved-ID root\n * bootstrap and task replacement. `scope` sets the default `tx.createTask()` conversation and the task attributed to\n * appended entries.\n */\n commitWith(change, context2, scope) {\n try {\n this.#assertUsable();\n } catch (error) {\n return Promise.reject(error);\n }\n return this.#enqueue(() => this.#runCommit(change, context2, scope));\n }\n /** Internal: run a read-only job on the mutation line so multi-read derivations observe one committed state. */\n readOnLine(job) {\n try {\n this.#assertUsable();\n } catch (error) {\n return Promise.reject(error);\n }\n return this.#enqueue(async () => {\n this.#assertHealthy();\n return job();\n });\n }\n /**\n * Internal: a conversation document's current incarnation and value, for a job already running on the line (see\n * `readOnLine()`). Absent documents are `undefined`.\n */\n async conversationDocumentOnLine(token, conversationId, context2) {\n const definition = token.definition;\n const resolved = resolveAddress(definition, [conversationId, context2]);\n const loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context2);\n if (loaded === void 0)\n return void 0;\n checkRecordScope(definition, loaded.record);\n checkRecordVersion(definition, loaded.record, loaded.storedVersion);\n return { record: loaded.record, version: loaded.valueVersion, value: loaded.tracker.value };\n }\n async snapshot(token, ...args) {\n this.#assertUsable();\n const definition = token.definition;\n const resolved = resolveAddress(definition, args);\n const context2 = args[resolved.nextArgument];\n const cached = this.#documents.get(resolved.id);\n const loaded = cached?.valueVersion === definition.version ? cached : await this.#enqueue(async () => {\n this.#assertHealthy();\n return this.#loadDocument(definition, resolved.id, resolved.address, context2);\n });\n if (loaded === void 0)\n return void 0;\n checkRecordScope(definition, loaded.record);\n checkRecordVersion(definition, loaded.record, loaded.storedVersion);\n return loaded.tracker.value;\n }\n documentState(token, ...args) {\n try {\n this.#assertUsable();\n const definition = token.definition;\n const resolved = resolveAddress(definition, args);\n const context2 = args[resolved.nextArgument];\n return this.#enqueue(async () => {\n this.#assertHealthy();\n const loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context2);\n if (loaded === void 0)\n return void 0;\n const { observer: source, detach } = this.#attachDocument(definition, loaded, (value, release) => new CommittedStateSource(value, release));\n try {\n return replicatedState(source);\n } catch (error) {\n detach();\n throw error;\n }\n });\n } catch (error) {\n return Promise.reject(error);\n }\n }\n async watchDoc(token, ...args) {\n this.#assertUsable();\n const definition = token.definition;\n const resolved = resolveAddress(definition, args);\n const context2 = args[resolved.nextArgument];\n const signal = context2.abortSignal;\n let cancelled = signal?.aborted ?? false;\n const markCancelled = () => {\n cancelled = true;\n };\n signal?.addEventListener(\"abort\", markCancelled, { once: true });\n try {\n const watch2 = await this.#enqueue(async () => {\n this.#assertHealthy();\n if (cancelled)\n throw cancellationError(signal);\n const loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context2);\n if (cancelled)\n throw cancellationError(signal);\n if (loaded === void 0)\n return void 0;\n return this.#attachDocument(definition, loaded, (value, release) => new CommittedWatch(value, release)).observer;\n });\n if (watch2 === void 0)\n return void 0;\n if (cancelled) {\n watch2.cancel();\n throw cancellationError(signal);\n }\n if (signal !== void 0)\n watch2.observeCancellation(signal);\n return watch2;\n } finally {\n signal?.removeEventListener(\"abort\", markCancelled);\n }\n }\n async snapshotAsOf(token, ...args) {\n this.#assertUsable();\n const definition = token.definition;\n const resolved = resolveAddress(definition, args);\n if (resolved.address.scope.kind !== \"conversation\") {\n throw new TypeError(\"Session.snapshotAsOf() requires a conversation document\");\n }\n const conversationId = resolved.address.scope.conversationId;\n const atValue = args[resolved.nextArgument];\n if (typeof atValue !== \"number\" || !Number.isSafeInteger(atValue)) {\n throw new TypeError(\"Session.snapshotAsOf() requires an entry ID\");\n }\n const at = idFromNumber(atValue);\n const context2 = args[resolved.nextArgument + 1];\n return this.#enqueue(async () => {\n this.#assertHealthy();\n const storedEntry = await this.#storage.entry(conversationId, at, context2);\n if (storedEntry === void 0) {\n throw new Error(`Entry ${at} is not visible from conversation ${conversationId}`);\n }\n const address = {\n ...resolved.address,\n scope: { kind: \"conversation\", conversationId: storedEntry.entry.conversationId }\n };\n const record = await this.#storage.findDocument(address, storedEntry.commitSeq, context2);\n if (record === void 0)\n return void 0;\n const stored = await this.#storage.document(record.id, storedEntry.commitSeq, context2);\n if (stored === void 0) {\n throw new Error(`Historical document ${record.id} (${record.kind}) cannot be read`);\n }\n return materializeDocument(definition, stored);\n });\n }\n close(context2) {\n if (this.#closing === void 0) {\n const cleanup = withoutAbortSignal(context2);\n this.#closing = Promise.resolve().then(() => this.beforeClose()).then(() => this.#enqueue(async () => {\n this.#commitListeners.clear();\n this.#documents.clear();\n await this.#storage.close(cleanup);\n }));\n const listeners = [...this.#closeListeners];\n this.#closeListeners.clear();\n for (const listener of listeners)\n listener();\n }\n return awaitWithContext(this.#closing, context2);\n }\n /**\n * Runs inside every transaction that creates or forks a conversation, after the conversation record is staged. A\n * plain Session stages nothing; a Harness stages its built-in documents.\n */\n conversationCreated(_tx, _record) {\n return Promise.resolve();\n }\n /** Runs after close seals admission and before the line closes Storage; must not reject. */\n beforeClose() {\n return Promise.resolve();\n }\n /** Register a synchronous post-adoption listener. It must not throw, block, or call Session operations. */\n subscribeCommits(listener) {\n this.#assertUsable();\n this.#commitListeners.add(listener);\n return () => this.#commitListeners.delete(listener);\n }\n /** Register a listener called synchronously when close begins. It must not throw, block, or call Session operations. */\n subscribeClose(listener) {\n this.#assertUsable();\n this.#closeListeners.add(listener);\n return () => this.#closeListeners.delete(listener);\n }\n /** Drop every loaded tracker on the mutation line; later access cold-loads from Storage. */\n unloadDocuments() {\n return this.#enqueue(async () => {\n this.#documents.clear();\n });\n }\n async #runCommit(change, context2, scope) {\n this.#assertHealthy();\n context2.abortSignal?.throwIfAborted();\n const tx = new Transaction(this.#host, context2, scope);\n let result;\n try {\n result = await change(tx);\n } catch (error) {\n await tx.settleFailure();\n throw error;\n }\n const writes = await tx.settleSuccess();\n if (writes.length === 0) {\n tx.discard();\n return result;\n }\n let seq;\n try {\n seq = await this.#storage.commit(writes, withoutAbortSignal(context2));\n } catch (error) {\n tx.discard();\n if (!(error instanceof StorageRejected))\n this.#poison = { error };\n throw error;\n }\n let documents;\n try {\n documents = tx.adopt(seq);\n } catch (error) {\n this.#poison = { error };\n throw error;\n }\n this.#publish(seq, writes, documents, context2);\n return result;\n }\n #publish(seq, writes, documents, context2) {\n if (this.#commitListeners.size === 0)\n return;\n const changes = [];\n for (const write of writes) {\n switch (write.type) {\n case \"conversation\":\n case \"entry\":\n case \"task\":\n case \"submission\":\n changes.push(write);\n }\n }\n for (const document of documents)\n changes.push(document);\n const publication = { seq, changes };\n for (const listener of [...this.#commitListeners])\n listener(publication, context2);\n }\n /**\n * Attach an observer to one committed incarnation: check the definition, then forward this incarnation's committed\n * changes and close. `detach` removes both subscriptions.\n */\n #attachDocument(definition, loaded, create) {\n checkRecordScope(definition, loaded.record);\n checkRecordVersion(definition, loaded.record, loaded.storedVersion);\n let unsubscribeCommit = () => {\n };\n let unsubscribeClose = () => {\n };\n const detach = () => {\n unsubscribeCommit();\n unsubscribeClose();\n };\n const observer = create(loaded.tracker.value, detach);\n const observed = { version: loaded.valueVersion };\n unsubscribeCommit = this.subscribeCommits((publication, context2) => {\n for (const change of publication.changes) {\n if (change.type !== \"document\" || change.record.id !== loaded.record.id)\n continue;\n const frameContext = observer instanceof CommittedStateSource ? withoutAbortSignal(context2) : context2;\n const ops = observedOperations(observed, change);\n if (ops.length === 0)\n continue;\n observer.advance(change.value, ops, frameContext);\n }\n });\n unsubscribeClose = this.subscribeClose(() => observer.closeSession());\n return { observer, detach };\n }\n async #loadDocument(definition, addressId2, address, context2) {\n const cached = this.#documents.get(addressId2);\n if (cached?.valueVersion === definition.version)\n return cached;\n if (cached !== void 0)\n this.#documents.delete(addressId2);\n const record = await this.#storage.findDocument(address, \"current\", context2);\n if (record === void 0)\n return void 0;\n const stored = await this.#storage.document(record.id, \"current\", context2);\n if (stored === void 0)\n throw new Error(`Current document ${record.id} (${record.kind}) cannot be read`);\n const value = materializeDocument(definition, stored);\n const loaded = {\n addressId: addressId2,\n record: stored.record,\n storedVersion: stored.version,\n valueVersion: definition.version,\n deltasSinceBase: stored.deltasSinceBase,\n tracker: track(value)\n };\n this.#documents.set(addressId2, loaded);\n return loaded;\n }\n #enqueue(job) {\n const run2 = this.#tail.then(job);\n this.#tail = run2.then(() => void 0, () => void 0);\n return run2;\n }\n #assertUsable() {\n if (this.#closing !== void 0)\n throw new Error(\"Session is closed\");\n this.#assertHealthy();\n }\n #assertHealthy() {\n if (this.#poison !== void 0) {\n throw new Error(\"Session is poisoned by a failed commit after storage admission; reopen it\", {\n cause: this.#poison.error\n });\n }\n }\n };\n function observedOperations(observed, change) {\n if (change.value === null)\n return RETIREMENT_OPERATIONS;\n if (change.version === observed.version)\n return change.ops;\n observed.version = change.version;\n return [[\"r\", change.value]];\n }\n function cancellationError(signal) {\n return signal.reason instanceof Error ? signal.reason : new DOMException(\"The operation was aborted\", \"AbortError\");\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/registry.js\n var SECTION_KEY = /^[a-z][a-z0-9_-]*$/;\n var BUILTIN_TASKS = [GenerationTask, ToolTask, CompactionTask];\n var RegistryState = class {\n #extensions;\n #byName;\n #tasks;\n constructor(extensions) {\n this.#extensions = extensions;\n this.#byName = new Map(extensions.map((extension) => [extension.name, extension]));\n const tasks = /* @__PURE__ */ new Map();\n for (const task of BUILTIN_TASKS)\n tasks.set(task.definition.name, task);\n for (const extension of extensions) {\n for (const task of extension.tasks ?? []) {\n const name = task.definition.name;\n if (tasks.has(name))\n throw new Error(`Task ${name} of extension ${extension.name} is already installed`);\n tasks.set(name, task);\n }\n }\n this.#tasks = tasks;\n }\n installed() {\n return this.#extensions;\n }\n extension(name) {\n return this.#byName.get(name);\n }\n tools() {\n return this.#extensions.flatMap((extension) => (extension.tools ?? []).map((tool) => ({ extension, tool })));\n }\n sections() {\n return this.#extensions.flatMap((extension) => (extension.sections ?? []).map((section2) => ({ extension, section: section2 })));\n }\n tasks() {\n return [...this.#tasks.values()];\n }\n task(name) {\n return this.#tasks.get(name);\n }\n };\n var RegistryImpl = class {\n #current = new RegistryState([]);\n #listeners = /* @__PURE__ */ new Set();\n snapshot() {\n return this.#current;\n }\n subscribe(listener) {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n }\n install(extension) {\n validateExtension(extension);\n const current = this.#current.installed();\n const index3 = current.findIndex((installed) => installed.name === extension.name);\n const next = index3 < 0 ? [...current, extension] : current.map((installed, at) => at === index3 ? extension : installed);\n this.#publish(next);\n }\n uninstall(extension) {\n const current = this.#current.installed();\n if (!current.some((installed) => installed.name === extension.name))\n return;\n this.#publish(current.filter((installed) => installed.name !== extension.name));\n }\n /** Build and validate the next state, which throws on a task name collision, then publish it synchronously. */\n #publish(extensions) {\n this.#current = new RegistryState(extensions);\n for (const listener of [...this.#listeners])\n listener();\n }\n };\n function validateExtension(extension) {\n const tools = /* @__PURE__ */ new Set();\n for (const tool of extension.tools ?? []) {\n if (tools.has(tool.name))\n throw new Error(`Extension ${extension.name} has two tools named ${tool.name}`);\n tools.add(tool.name);\n }\n const sections = /* @__PURE__ */ new Set();\n for (const { key } of extension.sections ?? []) {\n if (!SECTION_KEY.test(key))\n throw new TypeError(`Section key ${JSON.stringify(key)} must match ${SECTION_KEY}`);\n if (key === INSTRUCTIONS_KEY)\n throw new Error(`Section key ${key} is reserved for the agent's instructions`);\n if (sections.has(key))\n throw new Error(`Extension ${extension.name} has two sections with key ${key}`);\n sections.add(key);\n }\n }\n function createRegistry() {\n return new RegistryImpl();\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/scheduler.js\n var SCAN_PAGE_SIZE3 = 256;\n var MAX_TIMER_DELAY = 2147483647;\n var LIVE_STATUSES = [\"pending\", \"running\", \"waiting\", \"completing\"];\n var TaskScheduler = class {\n #session;\n #storage;\n #registry;\n #models;\n #agent;\n #settings;\n #env;\n #now;\n #report;\n #settleOutcome;\n #withdrawInputs;\n #conversation;\n #context;\n #live = /* @__PURE__ */ new Map();\n /**\n * Context range last read through a task runtime, per conversation: a later read, by any of its tasks, scans only\n * newer entries. `idleSince` is the Harness time it was first seen idle. Derived and never persisted; dropped at the\n * first idle check after `settings.contextRetentionMs` of idleness, and at close.\n */\n #contexts = /* @__PURE__ */ new Map();\n /** Timer for the earliest expiry of an idle context, only where timers can be unreferenced (see `#scheduleExpiry`). */\n #expiry;\n #invocations = /* @__PURE__ */ new Map();\n #taskWaiters = new Waiters();\n /** Idle waiters by conversation; `undefined` waits for the whole Harness. */\n #idleWaiters = new Waiters();\n /** Definition whose migration failed per task; retried only once the registry resolves another definition. */\n #failedMigrations = /* @__PURE__ */ new Map();\n /** Owner task of each loaded conversation, `null` when ownerless. */\n #edges = /* @__PURE__ */ new Map();\n /** Tasks that own a loaded conversation; their nodes stay in `#settled` once terminal. */\n #conversationOwners = /* @__PURE__ */ new Set();\n /** Ownership fields of terminal tasks that walks pass through. */\n #settled = /* @__PURE__ */ new Map();\n /**\n * `failFast` waiters the next reconcile checks for a failed task in `on`: at open, when they start waiting, and when\n * one of their tasks fails.\n */\n #failFastChecks = /* @__PURE__ */ new Set();\n #reconcileScheduled = false;\n #cascadePending = false;\n #unsubscribeRegistry = () => {\n };\n #enabled = false;\n #closing = false;\n #dirty = false;\n #draining = false;\n constructor(options) {\n this.#session = options.session;\n this.#storage = options.storage;\n this.#registry = options.registry;\n this.#models = options.models;\n this.#agent = options.agent;\n this.#settings = options.settings;\n this.#env = options.env;\n this.#now = options.now;\n this.#report = options.report;\n this.#settleOutcome = options.settleOutcome;\n this.#withdrawInputs = options.withdrawInputs;\n this.#conversation = options.conversation;\n this.#context = options.context;\n }\n /** Load live tasks and change surviving `running` tasks back to `pending`. Dispatches nothing. */\n async open(context2) {\n this.#session.subscribeCommits((publication) => this.#observe(publication));\n this.#session.subscribeClose(() => this.#seal());\n this.#unsubscribeRegistry = this.#registry.subscribe(() => this.#kick());\n await this.#session.commitWith(async (tx) => {\n const scans = [];\n for (const status of LIVE_STATUSES) {\n scans.push(await scanAll((cursor) => tx.scanTasks({ status }, SCAN_PAGE_SIZE3, cursor)));\n }\n for (const records of scans) {\n for (const record of records) {\n this.#live.set(record.id, record);\n if (record.state.status === \"running\") {\n tx.setTask(withState(record, { status: \"pending\", checkpoint: record.state.checkpoint }));\n }\n if (record.state.status === \"waiting\" && record.state.policy === \"failFast\") {\n this.#failFastChecks.add(record.id);\n }\n }\n }\n }, context2);\n this.#cascadePending = true;\n this.#scheduleReconcile();\n }\n /** Enable scheduling. Idempotent; the kick does nothing once closing. */\n resume() {\n this.#enabled = true;\n this.#kick();\n }\n /** Wait for every invocation signalled by `#seal()`. Writes nothing. */\n async join() {\n await Promise.allSettled([...this.#invocations.values()].map((invocation) => invocation.done));\n }\n /**\n * Commit the abort mark, or settle a task that no registered definition can take as `orphaned` when nothing it owns\n * is live, then join the run invocation seen on the line; the commit listener signalled it. The abort invocation\n * starts once the task's ordinary owned work is gone. A `completing` task is only marked.\n */\n async abort(id, context2) {\n const marked = await this.#session.commitWith(async (tx) => {\n const current = await tx.task(id);\n if (current === void 0)\n throw new Error(`Task ${id} does not exist`);\n if (current.state.status === \"terminal\")\n return { result: \"terminal\" };\n const invocation = this.#invocations.get(id);\n if (invocation === void 0 && current.state.status !== \"completing\") {\n await this.#loadScopes(false);\n if (!this.#ownedLive().has(id)) {\n const resolution = this.#resolve(current, this.#registry.snapshot());\n if (resolution.kind === \"blocked\") {\n await this.#terminate(tx, current, { status: \"orphaned\", reason: resolution.reason });\n return { result: \"marked\" };\n }\n }\n }\n if (!current.abortRequested)\n tx.setTask({ ...current, abortRequested: true });\n return { result: \"marked\", run: invocation?.mode === \"run\" ? invocation : void 0 };\n }, context2);\n if (marked.run !== void 0)\n await awaitWithContext(marked.run.done, context2);\n return marked.result;\n }\n async waitForTask(id, context2) {\n const found = await this.#session.readOnLine(async () => {\n if (this.#closing)\n throw closedError();\n if (this.#live.has(id))\n return { promise: this.#taskWaiters.add(id, context2) };\n const record = await this.#storage.task(id, context2);\n if (record === void 0)\n throw new Error(`Task ${id} does not exist`);\n return { promise: Promise.resolve(record) };\n });\n return found.promise;\n }\n /**\n * Resolve when ordinary traversal from the conversation, or from every ownerless conversation, reaches no live\n * non-background task.\n */\n waitForIdle(conversationId, context2) {\n if (this.#closing)\n return Promise.reject(closedError());\n if (this.#idle(conversationId))\n return Promise.resolve();\n this.#scheduleReconcile();\n return this.#idleWaiters.add(conversationId, context2);\n }\n /**\n * `Conversation.abort()`: in one commit, withdraw the queued inputs and mark every live non-background task that\n * ordinary traversal from the conversation reaches; resolves once the scope is idle. With `background`, traversal\n * crosses background boundaries, and the wait also covers every task it reached.\n */\n async abortConversation(conversationId, background, context2) {\n const reached = await this.#session.commitWith(async (tx) => {\n const queued2 = await this.#loadScopes(true);\n const scope = { conversation: conversationId };\n const reached2 = [];\n for (const record of this.#live.values()) {\n if (record.background && !background)\n continue;\n if (this.#inScope(parentOf(record), scope, background) !== true)\n continue;\n reached2.push(record.id);\n if (!record.abortRequested)\n tx.setTask({ ...record, abortRequested: true });\n }\n for (const id of queued2) {\n if (this.#inScope({ conversation: id }, scope, background) === true)\n await this.#withdrawInputs(tx, id);\n }\n return reached2;\n }, context2);\n if (background)\n for (const id of reached)\n await this.waitForTask(id, context2);\n await this.waitForIdle(conversationId, context2);\n }\n // ─── Scheduling ────────────────────────────────────────────────────────\n #observe(publication) {\n const updated = [];\n const failed = [];\n let changed = false;\n for (const change of publication.changes) {\n if (change.type !== \"task\")\n continue;\n changed = true;\n const record = change.value;\n const previous = this.#live.get(record.id);\n if (failedOutcome(record) && (previous === void 0 || !failedOutcome(previous)))\n failed.push(record.id);\n if (record.state.status === \"terminal\") {\n this.#live.delete(record.id);\n this.#failedMigrations.delete(record.id);\n this.#failFastChecks.delete(record.id);\n if (this.#conversationOwners.has(record.id))\n this.#settled.set(record.id, nodeOf(record));\n this.#taskWaiters.resolve(record.id, record);\n this.#scheduleReconcile();\n continue;\n }\n if (record.abortRequested && previous?.abortRequested !== true) {\n this.#cascadePending = true;\n const invocation = this.#invocations.get(record.id);\n if (invocation?.mode === \"run\")\n invocation.controller.abort();\n }\n const status = record.state.status;\n if (status === \"completing\" && previous?.state.status !== \"completing\") {\n if (cancellationIntent(record))\n this.#cascadePending = true;\n this.#scheduleReconcile();\n }\n if (status === \"waiting\" && record.state.policy === \"failFast\" && previous?.state.status !== \"waiting\") {\n this.#failFastChecks.add(record.id);\n this.#scheduleReconcile();\n }\n this.#live.set(record.id, record);\n updated.push(record);\n }\n for (const id of failed) {\n for (const record of this.#live.values()) {\n const state2 = record.state;\n if (state2.status === \"waiting\" && state2.policy === \"failFast\" && state2.on.includes(id)) {\n this.#failFastChecks.add(record.id);\n this.#scheduleReconcile();\n }\n }\n }\n for (const change of publication.changes) {\n if (change.type === \"conversation\" && !this.#edges.has(change.value.id)) {\n this.#setEdge(change.value.id, change.value.owner?.taskId ?? null);\n }\n }\n for (const change of publication.changes) {\n if (change.type !== \"submission\" || change.value.status !== \"queued\" || change.value.type !== \"input\")\n continue;\n const up = { conversation: change.value.conversationId };\n if (!this.#chainKnown(up) || this.#belowCancelled(up))\n this.#cascadePending = true;\n }\n for (const record of updated) {\n if (!this.#chainKnown(parentOf(record)))\n this.#scheduleReconcile();\n else if (!record.background && !record.abortRequested && this.#belowCancelled(parentOf(record))) {\n this.#cascadePending = true;\n }\n }\n if (this.#cascadePending)\n this.#scheduleReconcile();\n if (!changed)\n return;\n this.#settleIdle();\n this.#kick();\n }\n /**\n * `settings.contextRetentionMs`, or 0 when the host's settings throw. Kept contexts are only a cache, so dropping them\n * is safe, while a throw here would escape commit listeners, reconciliation, and the expiry timer.\n */\n #contextRetentionMs() {\n try {\n return this.#settings().contextRetentionMs;\n } catch (error) {\n this.#report(error);\n return 0;\n }\n }\n /** Resolve idle waiters, and drop each kept context whose conversation has been idle for the retention period. */\n #settleIdle() {\n for (const conversationId of this.#idleWaiters.keys()) {\n if (this.#idle(conversationId))\n this.#idleWaiters.resolve(conversationId);\n }\n const now = this.#now();\n const retention = this.#contextRetentionMs();\n for (const [conversationId, kept] of this.#contexts) {\n if (kept.idleSince !== void 0 && now - kept.idleSince >= retention) {\n this.#contexts.delete(conversationId);\n } else if (!this.#idle(conversationId)) {\n kept.idleSince = void 0;\n } else if (retention > 0) {\n kept.idleSince ??= now;\n } else {\n this.#contexts.delete(conversationId);\n }\n }\n this.#scheduleExpiry();\n }\n /**\n * Run `#settleIdle()` when the earliest idle context expires. The timer is unreferenced, so it never keeps the process\n * alive. Where timers cannot be unreferenced, as in Cloudflare Workers, none is kept: a pending timer could keep a\n * Durable Object from being evicted, and eviction frees the contexts. There, task changes alone check expiry.\n */\n #scheduleExpiry() {\n const retention = this.#contextRetentionMs();\n let at;\n for (const kept of this.#contexts.values()) {\n if (kept.idleSince !== void 0 && (at === void 0 || kept.idleSince + retention < at)) {\n at = kept.idleSince + retention;\n }\n }\n if (this.#expiry !== void 0 && this.#expiry.at === at)\n return;\n if (this.#expiry !== void 0)\n clearTimeout(this.#expiry.timer);\n this.#expiry = void 0;\n if (at === void 0 || this.#closing)\n return;\n const timer = setTimeout(() => {\n this.#expiry = void 0;\n this.#settleIdle();\n }, Math.min(Math.max(0, at - this.#now()), MAX_TIMER_DELAY));\n const unref = timer.unref;\n if (typeof unref !== \"function\") {\n clearTimeout(timer);\n return;\n }\n unref.call(timer);\n this.#expiry = { at, timer };\n }\n // ─── Ownership ───────────────────────────────────────────────────────────\n #scheduleReconcile() {\n if (this.#reconcileScheduled || this.#closing)\n return;\n this.#reconcileScheduled = true;\n queueMicrotask(() => void this.#reconcile());\n }\n /**\n * One commit that applies what committed records imply: abort marks below live owners with cancellation intent\n * (spec §5.4), `failFast` marks (spec §5.5), withdrawn queued inputs below cancelled owners, and the final terminal\n * record of every `completing` task whose ordinary owned work is gone. The durable records are the intent, so this\n * also repairs whatever a crash left unapplied. Resolves idle waiters that the loaded edges decide.\n */\n async #reconcile() {\n this.#reconcileScheduled = false;\n const cascade = this.#cascadePending;\n this.#cascadePending = false;\n const checks = [...this.#failFastChecks];\n this.#failFastChecks.clear();\n try {\n await this.#session.commitWith(async (tx) => {\n if (this.#closing)\n return;\n const queued2 = await this.#loadScopes(cascade);\n const marked = /* @__PURE__ */ new Set();\n const mark = (record) => {\n if (record.abortRequested || marked.has(record.id))\n return;\n marked.add(record.id);\n tx.setTask({ ...record, abortRequested: true });\n };\n for (const record of this.#live.values()) {\n if (!record.background && this.#belowCancelled(parentOf(record)))\n mark(record);\n }\n for (const id of checks) {\n const waiter = this.#live.get(id);\n if (waiter?.state.status !== \"waiting\" || !await this.#anyFailed(waiter.state.on))\n continue;\n for (const member of waiter.state.on) {\n const record = this.#live.get(member);\n if (record !== void 0 && !failedOutcome(record))\n mark(record);\n }\n }\n for (const id of queued2)\n if (this.#belowCancelled({ conversation: id }))\n await this.#withdrawInputs(tx, id);\n await this.#finalize(tx);\n }, this.#context);\n } catch (error) {\n this.#cascadePending = true;\n for (const id of checks)\n this.#failFastChecks.add(id);\n if (!this.#closing)\n this.#report(error);\n }\n this.#settleIdle();\n }\n /** Whether any of `ids` holds or ended with an outcome other than `completed`. */\n async #anyFailed(ids) {\n for (const id of ids) {\n const record = this.#live.get(id) ?? await this.#storage.task(id, this.#context);\n if (record !== void 0 && failedOutcome(record))\n return true;\n }\n return false;\n }\n /**\n * Write the terminal record of every `completing` task without live ordinary owned work. Finalizing one can free its\n * owner, so this repeats over the commit's candidates until nothing changes. A held scheduler outcome gets its\n * Harness cleanup here.\n */\n async #finalize(tx) {\n for (; ; ) {\n const overlay = overlayOf(tx);\n const owned = this.#ownedLive(overlay);\n const done = [...this.#liveRecords(overlay)].filter((record) => record.state.status === \"completing\" && !owned.has(record.id));\n if (done.length === 0)\n return;\n for (const record of done) {\n const outcome = record.state.outcome;\n tx.setTask(withState(record, { status: \"terminal\", outcome }));\n if (outcome.status === \"faulted\" || outcome.status === \"orphaned\") {\n await this.#settleOutcome(tx, record, outcome);\n }\n }\n }\n }\n /**\n * Load the owner chains of every live task and, with `queued`, of every conversation with queued submissions, on the\n * Session line; returns the latter. Reads committed Storage directly, so it may run inside a commit callback.\n */\n async #loadScopes(queued2) {\n for (const record of [...this.#live.values()]) {\n if (!this.#chainKnown(parentOf(record)))\n await this.#loadChain(parentOf(record));\n }\n if (!queued2)\n return [];\n const submissions = await scanAll((cursor) => this.#storage.scanSubmissions({ status: \"queued\" }, SCAN_PAGE_SIZE3, cursor, this.#context));\n const conversations = [...new Set(submissions.map((submission) => submission.conversationId))];\n for (const id of conversations)\n await this.#loadChain({ conversation: id });\n return conversations;\n }\n /** Load the owner edges and task nodes from `start` up to its ownerless root. */\n async #loadChain(start, overlay) {\n let at = start;\n while (at !== void 0) {\n if (\"task\" in at) {\n let node = this.#node(at.task, overlay);\n if (node === void 0) {\n const record = await this.#storage.task(at.task, this.#context);\n if (record === void 0)\n return;\n node = nodeOf(record);\n if (record.state.status === \"terminal\")\n this.#settled.set(record.id, node);\n }\n at = parentOf(node);\n } else {\n let edge = this.#edge(at.conversation, overlay);\n if (edge === void 0) {\n const record = await this.#storage.conversation(at.conversation, this.#context);\n edge = record?.owner?.taskId ?? null;\n this.#setEdge(at.conversation, edge);\n }\n at = edge === null ? void 0 : { task: edge };\n }\n }\n }\n #setEdge(conversationId, owner) {\n this.#edges.set(conversationId, owner);\n if (owner !== null)\n this.#conversationOwners.add(owner);\n }\n /** Owner task of a conversation, `null` when ownerless, `undefined` while not loaded. */\n #edge(id, overlay) {\n return overlay?.edges.has(id) === true ? overlay.edges.get(id) : this.#edges.get(id);\n }\n #node(id, overlay) {\n return overlay?.tasks.get(id) ?? this.#live.get(id) ?? this.#settled.get(id);\n }\n /** Walk up from `start`: owner tasks and conversations, ending at an ownerless root or an edge not loaded yet. */\n *#above(start, overlay) {\n let at = start;\n while (at !== void 0) {\n if (\"task\" in at) {\n const node = this.#node(at.task, overlay);\n if (node === void 0) {\n yield { unknown: true };\n return;\n }\n yield { task: at.task, node };\n at = parentOf(node);\n } else {\n yield { conversation: at.conversation };\n const edge = this.#edge(at.conversation, overlay);\n if (edge === void 0) {\n yield { unknown: true };\n return;\n }\n at = edge === null ? void 0 : { task: edge };\n }\n }\n }\n /** Whether every owner above `start` is loaded. */\n #chainKnown(start, overlay) {\n for (const step of this.#above(start, overlay))\n if (\"unknown\" in step)\n return false;\n return true;\n }\n /** Live records, with the overlay's candidates replacing committed ones; terminal candidates are gone. */\n *#liveRecords(overlay) {\n for (const record of this.#live.values()) {\n const candidate = overlay?.tasks.get(record.id) ?? record;\n if (candidate.state.status !== \"terminal\")\n yield candidate;\n }\n if (overlay === void 0)\n return;\n for (const record of overlay.tasks.values()) {\n if (!this.#live.has(record.id) && record.state.status !== \"terminal\")\n yield record;\n }\n }\n /**\n * Every task with live ordinary owned work (spec §5.5), mapped to that work: each live non-background task counts for\n * every owner task above it up to and including the first background one. Owner chains must be loaded.\n */\n #ownedLive(overlay) {\n const owned = /* @__PURE__ */ new Map();\n for (const record of this.#liveRecords(overlay)) {\n if (record.background)\n continue;\n for (const step of this.#above(parentOf(record), overlay)) {\n if (\"unknown\" in step)\n break;\n if (!(\"task\" in step))\n continue;\n const below = owned.get(step.task);\n if (below === void 0)\n owned.set(step.task, [record.id]);\n else\n below.push(record.id);\n if (step.node.background)\n break;\n }\n }\n return owned;\n }\n /**\n * Whether ordinary traversal from `scope` reaches `start`: walking up reaches the scope's conversation, or an\n * ownerless one for `roots`, without crossing a background owner, unless `crossBackground`. `undefined` while an\n * edge is not loaded.\n */\n #inScope(start, scope, crossBackground = false) {\n for (const step of this.#above(start)) {\n if (\"unknown\" in step)\n return void 0;\n if (\"conversation\" in step) {\n if (\"conversation\" in scope && step.conversation === scope.conversation)\n return true;\n } else if (step.node.background && !crossBackground) {\n return false;\n }\n }\n return \"roots\" in scope;\n }\n /**\n * Whether a live owner's cancellation intent reaches `start`: walking up finds an owner with intent before a\n * background owner without it. Terminal owners never cascade (spec §5.4).\n */\n #belowCancelled(start) {\n for (const step of this.#above(start)) {\n if (\"unknown\" in step)\n return false;\n if (!(\"task\" in step))\n continue;\n const live = this.#live.get(step.task);\n if (live !== void 0 && cancellationIntent(live))\n return true;\n if (step.node.background)\n return false;\n }\n return false;\n }\n /** Close listener: runs synchronously once admission is sealed, before `join()`. */\n #seal() {\n this.#closing = true;\n this.#unsubscribeRegistry();\n const error = closedError();\n this.#taskWaiters.rejectAll(error);\n this.#idleWaiters.rejectAll(error);\n this.#contexts.clear();\n if (this.#expiry !== void 0)\n clearTimeout(this.#expiry.timer);\n this.#expiry = void 0;\n for (const invocation of this.#invocations.values())\n invocation.controller.abort();\n }\n #kick() {\n this.#dirty = true;\n if (this.#draining || !this.#enabled || this.#closing)\n return;\n this.#draining = true;\n queueMicrotask(() => void this.#drain());\n }\n async #drain() {\n try {\n while (this.#dirty && this.#enabled && !this.#closing) {\n this.#dirty = false;\n for (const reservation of await this.#reserve())\n this.#start(reservation);\n }\n } catch (error) {\n if (!this.#closing)\n this.#report(error);\n } finally {\n this.#draining = false;\n if (this.#dirty)\n this.#kick();\n }\n }\n /** Reserve every eligible task in one commit; orphan abort-marked tasks no definition can take. */\n async #reserve() {\n const reservations = [];\n try {\n await this.#session.commitWith(async (tx) => {\n if (!this.#enabled || this.#closing)\n return;\n await this.#loadScopes(false);\n const owned = this.#ownedLive();\n let snapshot;\n for (const record of [...this.#live.values()]) {\n if (this.#invocations.has(record.id) || this.#waitingOn(record, owned).length > 0)\n continue;\n if (record.state.status === \"completing\")\n continue;\n const runnable = record;\n const mode = record.abortRequested ? \"abort\" : \"run\";\n snapshot ??= this.#registry.snapshot();\n const resolution = this.#resolve(runnable, snapshot);\n if (resolution.kind === \"blocked\") {\n if (mode === \"abort\") {\n await this.#terminate(tx, record, { status: \"orphaned\", reason: resolution.reason });\n }\n continue;\n }\n if (resolution.record !== runnable || record.state.status !== \"running\") {\n tx.setTask(withState(resolution.record, {\n status: \"running\",\n checkpoint: resolution.record.state.checkpoint\n }));\n }\n const invocation = this.#createInvocation(record, mode);\n reservations.push({ invocation, task: resolution.task, snapshot });\n }\n }, this.#context);\n } catch (error) {\n for (const { invocation } of reservations) {\n this.#invocations.delete(invocation.taskId);\n invocation.finish();\n }\n throw error;\n }\n return reservations;\n }\n /**\n * Live tasks a task waits for before its next invocation: its live ordinary owned work when abort-marked, since\n * abort runs bottom-up, otherwise the live part of the `on` of a wait.\n */\n #waitingOn(record, owned) {\n if (record.abortRequested)\n return owned.get(record.id) ?? [];\n if (record.state.status !== \"waiting\")\n return [];\n return record.state.on.filter((id) => this.#live.has(id));\n }\n /** Resolve the record's definition by kind, migrating an older stored version. */\n #resolve(record, snapshot) {\n const fit = this.#fit(record, snapshot.task(record.kind));\n if (\"reason\" in fit)\n return { kind: \"blocked\", reason: fit.reason };\n if (!fit.migrates)\n return { kind: \"ready\", task: fit.task, record };\n const definition = erased(fit.task);\n try {\n if (definition.migrate === void 0)\n throw missingMigration(record, definition);\n const migrated = definition.migrate(record.input, record.state.checkpoint, record.version);\n const state2 = { ...record.state, checkpoint: copyJson(migrated.checkpoint) };\n const migratedRecord = { ...record, version: definition.version, input: copyJson(migrated.input), state: state2 };\n return { kind: \"ready\", task: fit.task, record: migratedRecord };\n } catch (error) {\n this.#failedMigrations.set(record.id, { task: fit.task, error });\n this.#report(error);\n return { kind: \"blocked\", reason: \"migration_failed\" };\n }\n }\n #fit(record, task) {\n if (task === void 0)\n return { reason: \"missing_task\" };\n const version = task.definition.version;\n if (version === record.version)\n return { task, migrates: false };\n if (version < record.version)\n return { reason: \"task_too_old\" };\n const failed = this.#failedMigrations.get(record.id);\n if (failed?.task === task)\n return { reason: \"migration_failed\", error: failed.error };\n return { task, migrates: true };\n }\n /**\n * Scheduling state and every live task with its derived state, read on the Session line. Runs no task code: a\n * pending migration shows as `ready` with `migrates`, and only a migration the scheduler already tried, or one that\n * cannot exist, shows as failed.\n */\n async inspect(snapshot) {\n await this.#loadScopes(false);\n const owned = this.#ownedLive();\n const tasks = [];\n for (const record of this.#live.values()) {\n tasks.push({ record, state: this.#inspectTask(record, snapshot, owned) });\n }\n const scheduling = this.#closing ? \"closing\" : this.#enabled ? \"running\" : \"paused\";\n return { scheduling, tasks };\n }\n #inspectTask(record, snapshot, owned) {\n if (this.#invocations.has(record.id))\n return { kind: \"running\" };\n if (record.state.status === \"completing\")\n return { kind: \"completing\" };\n const on = this.#waitingOn(record, owned);\n if (on.length > 0)\n return { kind: \"waiting\", on };\n const fit = this.#fit(record, snapshot.task(record.kind));\n if (\"reason\" in fit)\n return { kind: \"blocked\", ...fit };\n if (fit.migrates && fit.task.definition.migrate === void 0) {\n return { kind: \"blocked\", reason: \"migration_failed\", error: missingMigration(record, erased(fit.task)) };\n }\n return { kind: \"ready\", migrates: fit.migrates };\n }\n #createInvocation(record, mode) {\n const controller = new AbortController();\n const { promise: done, resolve: finish } = Promise.withResolvers();\n const invocation = {\n taskId: record.id,\n conversationId: record.conversationId,\n mode,\n controller,\n context: withAbortSignal(controller.signal, this.#context),\n watches: /* @__PURE__ */ new Set(),\n ended: false,\n done,\n finish: () => finish()\n };\n this.#invocations.set(record.id, invocation);\n return invocation;\n }\n #start(reservation) {\n const invocation = reservation.invocation;\n void (async () => {\n try {\n if (invocation.mode === \"run\")\n await this.#run(reservation);\n else\n await this.#runAbort(reservation);\n } catch (error) {\n this.#report(error);\n } finally {\n this.#end(invocation);\n invocation.finish();\n this.#kick();\n }\n })();\n }\n /** Run phase handlers, each preceded by a step that decides on the line whether the invocation continues. */\n async #run(reservation) {\n const invocation = reservation.invocation;\n const state2 = { task: reservation.task, snapshot: reservation.snapshot, reported: void 0 };\n const phase = { snapshot: () => state2.snapshot, task: () => state2.task, agent: void 0 };\n const runtime = this.#runtime(invocation, phase);\n let previous;\n for (; ; ) {\n const current = await this.#step(invocation, (tx, current2) => this.#decide(tx, current2, previous, state2));\n if (current === void 0 || this.#closing)\n return;\n const checkpoint = current.state.checkpoint;\n phase.agent = void 0;\n try {\n await erased(state2.task).phases[checkpoint.phase](current, runtime, invocation.context);\n previous = { checkpoint };\n } catch (error) {\n previous = { checkpoint, failure: { error } };\n }\n }\n }\n /**\n * Precedence rules for a run invocation, on the line. Rules 1 (terminal, `completing`, or `waiting`) and 2 (closing)\n * are applied by `#step`. Returns whether the invocation continues with the next phase.\n */\n #decide(tx, current, previous, state2) {\n if (current.abortRequested)\n return false;\n if (previous === void 0)\n return true;\n if (previous.failure !== void 0)\n return { fault: previous.failure.error };\n if (jsonEqual(current.state.checkpoint, previous.checkpoint)) {\n const message = `Task ${current.kind} phase ${previous.checkpoint.phase} returned without durable progress`;\n return { fault: new Error(message) };\n }\n state2.snapshot = this.#registry.snapshot();\n const next = state2.snapshot.task(current.kind);\n if (next !== state2.task) {\n if (next !== void 0 && canReserve(next, current)) {\n tx.setTask(withState(current, { status: \"pending\", checkpoint: current.state.checkpoint }));\n return false;\n }\n if (state2.reported === void 0 || state2.reported.task !== next) {\n state2.reported = { task: next };\n const cause = next === void 0 ? \"missing_task\" : \"incompatible_task\";\n this.#report(new Error(`Task ${current.id} keeps running under its old ${current.kind} definition`, { cause }));\n }\n }\n return true;\n }\n /** Run the abort handler once; rules 1, 2, and 4 apply, and returning without an outcome faults. */\n async #runAbort(reservation) {\n const invocation = reservation.invocation;\n const current = this.#live.get(invocation.taskId);\n if (current === void 0 || this.#closing)\n return;\n let failure;\n try {\n const phase = { snapshot: () => reservation.snapshot, task: () => reservation.task, agent: void 0 };\n const runtime = this.#runtime(invocation, phase);\n await erased(reservation.task).abort(current, runtime, invocation.context);\n } catch (error) {\n failure = { error };\n }\n const message = `Abort handler of task ${invocation.taskId} returned without a terminal outcome`;\n await this.#step(invocation, () => ({ fault: failure?.error ?? new Error(message) }));\n }\n /**\n * One synchronous decision on the Session line. A task that is no longer running (rule 1: terminal, `completing`, or\n * `waiting`) or a closing Harness (rule 2) ends the invocation without a write; otherwise `decide` may stage a write\n * and returns whether the invocation continues. Ending happens inside the callback, before a fault's Harness\n * cleanup. A rejected step, such as admission after close, also ends the invocation.\n */\n async #step(invocation, decide) {\n try {\n return await this.#session.commitWith(async (tx) => {\n const found = this.#live.get(invocation.taskId);\n const current = found?.state.status === \"running\" ? found : void 0;\n const decision = current !== void 0 && !this.#closing ? decide(tx, current) : false;\n if (decision === true)\n return current;\n this.#end(invocation);\n if (decision !== false) {\n const message = decision.fault instanceof Error ? decision.fault.message : String(decision.fault);\n await this.#terminate(tx, current, { status: \"faulted\", error: { message } });\n }\n return void 0;\n }, this.#context);\n } catch (error) {\n this.#end(invocation);\n if (!this.#closing)\n this.#report(error);\n return void 0;\n }\n }\n /**\n * Write an outcome the scheduler decided. While the task's ordinary owned work is live it holds as `completing` and\n * its Harness cleanup waits for the final commit (spec §5.5, rule 4); otherwise it is terminal with its cleanup.\n */\n async #terminate(tx, record, outcome) {\n await this.#loadScopes(false);\n if (this.#ownedLive(overlayOf(tx)).has(record.id)) {\n tx.setTask(withState(record, { status: \"completing\", outcome }));\n return;\n }\n tx.setTask(withState(record, { status: \"terminal\", outcome }));\n await this.#settleOutcome(tx, record, outcome);\n }\n /**\n * Replace a running task's state with what it committed. A terminal state holds as `completing` while ordinary owned\n * work is live, judged on the commit's candidates, so work the same commit creates below the task counts. A wait is\n * validated first.\n */\n async #commitState(tx, invocation, current, next) {\n if (next.status === \"waiting\")\n await this.#validateWait(tx, invocation, current, next.on, next.policy);\n if (next.status === \"terminal\") {\n const overlay = overlayOf(tx);\n await this.#loadScopes(false);\n for (const record of overlay.tasks.values())\n await this.#loadChain(parentOf(record), overlay);\n if (this.#ownedLive(overlay).has(current.id)) {\n tx.setTask(withState(current, { status: \"completing\", outcome: next.outcome }));\n return;\n }\n }\n tx.setTask(withState(current, next));\n }\n /**\n * A wait names existing tasks other than the waiter and its owners, which could never finish first; `failFast` only\n * tasks the waiter owns. An abort handler cannot wait.\n */\n async #validateWait(tx, invocation, current, on, policy) {\n if (invocation.mode === \"abort\")\n throw new Error(`Abort handler of task ${current.id} cannot wait`);\n const overlay = overlayOf(tx);\n await this.#loadChain(parentOf(current));\n const owners = /* @__PURE__ */ new Set();\n for (const step of this.#above(parentOf(current)))\n if (\"task\" in step)\n owners.add(step.task);\n for (const id of on) {\n if (id === current.id || owners.has(id)) {\n throw new Error(`Task ${current.id} cannot wait on itself or its owner ${id}`);\n }\n const member = overlay.tasks.get(id) ?? this.#live.get(id) ?? await this.#storage.task(id, this.#context);\n if (member === void 0)\n throw new Error(`Task ${id} does not exist`);\n if (policy === \"failFast\" && member.owner !== current.id) {\n throw new Error(`Task ${current.id} can wait failFast only on tasks it owns; ${id} is not one`);\n }\n }\n }\n /** End an invocation: its runtime operations reject from now on, its signal aborts, its watches stop, and its task is free. */\n #end(invocation) {\n if (invocation.ended)\n return;\n invocation.ended = true;\n if (this.#invocations.get(invocation.taskId) === invocation)\n this.#invocations.delete(invocation.taskId);\n for (const watch2 of invocation.watches)\n void watch2.stop();\n invocation.controller.abort(endedError(invocation));\n }\n /** No live non-background task in the scope; a task whose owner edges are not loaded yet counts as inside. */\n #idle(conversationId) {\n const scope = conversationId === void 0 ? { roots: true } : { conversation: conversationId };\n for (const record of this.#live.values()) {\n if (!record.background && this.#inScope(parentOf(record), scope) !== false)\n return false;\n }\n return true;\n }\n // ─── Invocation runtime ──────────────────────────────────────────────────\n #runtime(invocation, phase) {\n const agent = () => {\n if (invocation.ended)\n return Promise.reject(endedError(invocation));\n if (phase.agent === void 0) {\n phase.agent = this.#agent(invocation.conversationId, phase.snapshot(), invocation.context);\n phase.agent.catch(() => {\n });\n }\n return phase.agent;\n };\n const hooks = {\n each: async (name, invoke) => {\n for (const handlers of agentHooks(await agent(), phase.task().definition.name)) {\n const handler = handlers[name];\n if (typeof handler !== \"function\")\n continue;\n try {\n await invoke(handler.bind(handlers));\n } catch (error) {\n if (invocation.controller.signal.aborted)\n throw error;\n this.#report(error);\n }\n }\n }\n };\n const settings2 = this.#settings;\n return {\n taskId: invocation.taskId,\n conversationId: invocation.conversationId,\n signal: invocation.controller.signal,\n models: this.#models,\n agent: (context2) => invocation.ended ? Promise.reject(endedError(invocation)) : awaitWithContext(agent(), context2),\n get settings() {\n return settings2();\n },\n env: (context2) => this.#read(invocation, () => this.#env(invocation.conversationId, context2)),\n hooks,\n get registry() {\n return phase.snapshot();\n },\n commit: (change, context2) => this.#gated(invocation, async (tx, current) => {\n const next = await change(tx, current);\n if (next !== void 0)\n await this.#commitState(tx, invocation, current, next);\n }, context2),\n memo: ((name, ...rest) => {\n if (rest.length === 1) {\n return this.#read(invocation, async () => memoOf(this.#live.get(invocation.taskId), name));\n }\n const candidate = rest[0];\n return this.#gated(invocation, (tx, current) => {\n const winner = memoOf(current, name);\n if (winner !== void 0)\n return winner;\n tx.setTask({ ...current, memos: { ...current.memos, [name]: candidate } });\n return candidate;\n }, rest[1]);\n }),\n sleep: (until, context2) => this.#sleep(invocation, until, context2),\n watchDoc: ((...args) => this.#watchDoc(invocation, args)),\n snapshot: ((...args) => this.#read(invocation, () => sessionMethod(this.#session, \"snapshot\")(...args))),\n snapshotAsOf: ((...args) => this.#read(invocation, () => sessionMethod(this.#session, \"snapshotAsOf\")(...args))),\n getTask: ((id, context2) => this.#read(invocation, () => this.#session.readOnLine(() => this.#storage.task(id, context2)))),\n waitForTask: ((id, context2) => this.#read(invocation, () => this.waitForTask(id, withAbortSignal(invocation.controller.signal, context2)))),\n outcomes: ((ids, context2) => this.#read(invocation, () => this.#session.readOnLine(async () => {\n const outcomes = [];\n for (const id of ids) {\n const state2 = (await this.#storage.task(id, context2))?.state;\n if (state2?.status !== \"terminal\")\n throw new Error(`Task ${id} is not terminal`);\n outcomes.push(state2.outcome);\n }\n return outcomes;\n }))),\n conversation: (id, context2) => this.#read(invocation, () => this.#conversation(id, {\n signal: invocation.controller.signal,\n check: () => {\n if (invocation.ended)\n throw endedError(invocation);\n }\n }, context2)),\n entry: ((...args) => {\n const [token, id, context2] = args.length === 2 ? [void 0, args[0], args[1]] : [args[0], args[1], args[2]];\n return this.#read(invocation, async () => {\n const found = await this.#session.readOnLine(() => this.#storage.entry(invocation.conversationId, id, context2));\n const entry = found?.entry;\n return token === void 0 || entry?.kind === token.kind ? entry : void 0;\n });\n }),\n context: (conversationId, context2, options) => this.#read(invocation, async () => {\n const { view, range } = await readContextFrom(this.#session, this.#storage, conversationId, context2, options?.at, this.#contexts.get(conversationId)?.range);\n const kept = this.#contexts.get(conversationId);\n if (range !== void 0 && !this.#closing && !invocation.ended && (kept === void 0 || kept.range.bounds.tail <= range.bounds.tail)) {\n if (!this.#idle(conversationId)) {\n this.#contexts.set(conversationId, { range, idleSince: void 0 });\n } else if (this.#contextRetentionMs() > 0) {\n this.#contexts.set(conversationId, { range, idleSince: kept?.idleSince ?? this.#now() });\n this.#scheduleExpiry();\n }\n }\n return view;\n }),\n now: () => {\n if (invocation.ended)\n throw endedError(invocation);\n return this.#now();\n },\n report: (error) => {\n if (invocation.ended)\n throw endedError(invocation);\n this.#report(error);\n }\n };\n }\n /** Run a committed-state read unless the invocation has ended. */\n async #read(invocation, read2) {\n if (invocation.ended)\n throw endedError(invocation);\n return read2();\n }\n /** Commit after rereading the task on the line and gating the invocation. */\n #gated(invocation, change, context2) {\n if (invocation.ended)\n return Promise.reject(endedError(invocation));\n return this.#session.commitWith(async (tx) => {\n if (invocation.ended)\n throw endedError(invocation);\n if (this.#closing)\n throw closedError();\n const found = this.#live.get(invocation.taskId);\n if (found === void 0)\n throw new Error(`Task ${invocation.taskId} is terminal`);\n if (found.state.status !== \"running\")\n throw new Error(`Task ${invocation.taskId} is ${found.state.status}`);\n const current = found;\n if (invocation.mode === \"run\" && current.abortRequested) {\n throw new Error(`Task ${invocation.taskId} has a durable abort mark`);\n }\n return change(tx, current);\n }, context2, { conversationId: invocation.conversationId, taskId: invocation.taskId });\n }\n /** Wait until the Harness clock reaches `until`, rechecking it after every timer. */\n async #sleep(invocation, until, context2) {\n if (invocation.ended)\n throw endedError(invocation);\n const signals2 = [invocation.controller.signal];\n if (context2.abortSignal !== void 0)\n signals2.push(context2.abortSignal);\n const signal = AbortSignal.any(signals2);\n for (; ; ) {\n signal.throwIfAborted();\n const remaining = until - this.#now();\n if (remaining <= 0)\n return;\n await delay(Math.min(remaining, MAX_TIMER_DELAY), signal);\n }\n }\n async #watchDoc(invocation, args) {\n if (invocation.ended)\n throw endedError(invocation);\n const watch2 = await sessionMethod(this.#session, \"watchDoc\")(...args);\n if (watch2 === void 0)\n return void 0;\n if (invocation.ended) {\n void watch2.stop();\n throw endedError(invocation);\n }\n invocation.watches.add(watch2);\n void watch2.closed.then(() => invocation.watches.delete(watch2));\n return watch2;\n }\n };\n function cancellationIntent(record) {\n return record.state.status !== \"terminal\" && (record.abortRequested || failedOutcome(record));\n }\n function failedOutcome(record) {\n const state2 = record.state;\n return (state2.status === \"completing\" || state2.status === \"terminal\") && state2.outcome.status !== \"completed\";\n }\n function parentOf(node) {\n return node.owner !== void 0 ? { task: node.owner } : { conversation: node.conversationId };\n }\n function nodeOf(record) {\n return {\n conversationId: record.conversationId,\n ...record.owner === void 0 ? {} : { owner: record.owner },\n background: record.background\n };\n }\n function overlayOf(tx) {\n const tasks = new Map(tx.stagedTasks().map((record) => [record.id, record]));\n const edges = new Map(tx.stagedConversations().map((record) => [record.id, record.owner?.taskId ?? null]));\n return { tasks, edges };\n }\n function memoOf(record, name) {\n const memos = record?.memos;\n return memos !== void 0 && Object.hasOwn(memos, name) ? memos[name] : void 0;\n }\n function sessionMethod(session, name) {\n return session[name].bind(session);\n }\n function missingMigration(record, definition) {\n return new Error(`Task ${record.kind} version ${definition.version} has no migration from ${record.version}`);\n }\n function erased(task) {\n return task.definition;\n }\n function endedError(invocation) {\n return new Error(`Task ${invocation.taskId} invocation has ended`);\n }\n function withState(record, state2) {\n if (state2.status !== \"terminal\" && state2.status !== \"completing\")\n return { ...record, state: state2 };\n const { memos: _memos, ...rest } = record;\n return { ...rest, state: state2 };\n }\n function canReserve(task, record) {\n const definition = task.definition;\n return definition.version === record.version || definition.version > record.version && definition.migrate !== void 0;\n }\n function delay(ms, signal) {\n return new Promise((resolve2, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal.reason);\n };\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve2();\n }, ms);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n function jsonEqual(left, right) {\n if (left === right)\n return true;\n if (typeof left !== \"object\" || typeof right !== \"object\" || left === null || right === null)\n return false;\n if (Array.isArray(left) || Array.isArray(right)) {\n if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length)\n return false;\n return left.every((value, index3) => jsonEqual(value, right[index3]));\n }\n const keys = Object.keys(left);\n if (keys.length !== Object.keys(right).length)\n return false;\n return keys.every((key) => Object.hasOwn(right, key) && jsonEqual(left[key], right[key]));\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/task-graph.js\n var LIVE_STATUSES2 = [\"pending\", \"running\", \"waiting\", \"completing\"];\n var SCAN_PAGE_SIZE4 = 256;\n var TaskGraphView = class {\n #session;\n #storage;\n #mount;\n #closed = false;\n constructor(session, storage) {\n this.#session = session;\n this.#storage = storage;\n session.subscribeCommits((publication, context2) => {\n if (this.#mount !== void 0)\n advance2(this.#mount, publication, context2);\n });\n session.subscribeClose(() => {\n this.#closed = true;\n for (const observer of [...this.#mount?.observers ?? []])\n observer.closeSession();\n this.#mount = void 0;\n });\n }\n /** A disposable read-only Chord state of the graph. */\n async state(context2) {\n const { observer, detach } = await this.#attach((value, release) => new CommittedStateSource(value, release), context2);\n try {\n return replicatedState(observer);\n } catch (error) {\n detach();\n throw error;\n }\n }\n /** A serialized exact-frame watch of the graph; cancelling `context` stops it. */\n async watch(context2) {\n const { observer } = await this.#attach((value, release) => new CommittedWatch(value, release), context2);\n const signal = context2.abortSignal;\n if (signal?.aborted) {\n observer.cancel();\n throw signal.reason;\n }\n if (signal !== void 0)\n observer.observeCancellation(signal);\n return observer;\n }\n /** Register an observer created from the current revision, atomically on the Session line. */\n #attach(create, context2) {\n return this.#session.readOnLine(async () => {\n const mount = this.#mount ?? { value: await this.#build(context2), observers: /* @__PURE__ */ new Set() };\n const detach = () => {\n mount.observers.delete(observer);\n if (mount.observers.size === 0 && this.#mount === mount)\n this.#mount = void 0;\n };\n const observer = create(mount.value, detach);\n if (this.#closed)\n throw closedError();\n context2.abortSignal?.throwIfAborted();\n this.#mount = mount;\n mount.observers.add(observer);\n return { observer, detach };\n });\n }\n async #build(context2) {\n const tasks = {};\n const records = [];\n for (const status of LIVE_STATUSES2) {\n records.push(...await scanAll((cursor) => this.#storage.scanTasks({ status }, SCAN_PAGE_SIZE4, cursor, context2)));\n }\n records.sort((a, b) => a.id - b.id);\n for (const record of records) {\n const owned = await scanAll((cursor) => this.#storage.scanConversations({ ownerTaskId: record.id }, SCAN_PAGE_SIZE4, cursor, context2));\n const conversations = owned.map((conversation2) => conversation2.id).sort((a, b) => a - b);\n tasks[String(record.id)] = nodeOf2(record, conversations);\n }\n return { tasks };\n }\n };\n function advance2(mount, publication, context2) {\n const ops = [];\n const changed = /* @__PURE__ */ new Map();\n const node = (key) => changed.has(key) ? changed.get(key) : mount.value.tasks[key];\n for (const change of publication.changes) {\n if (change.type !== \"task\")\n continue;\n const record = change.value;\n const key = String(record.id);\n const previous = node(key);\n if (record.state.status === \"terminal\") {\n if (previous === void 0)\n continue;\n ops.push([\"d\", [\"tasks\", key]]);\n changed.set(key, void 0);\n continue;\n }\n const next = nodeOf2(record, previous?.conversations ?? []);\n if (previous !== void 0 && JSON.stringify(next) === JSON.stringify(previous))\n continue;\n ops.push([\"s\", [\"tasks\", key], next]);\n changed.set(key, next);\n }\n const created = /* @__PURE__ */ new Map();\n for (const change of publication.changes) {\n if (change.type !== \"conversation\" || change.value.owner === void 0)\n continue;\n const key = String(change.value.owner.taskId);\n if (node(key) !== void 0)\n created.set(key, [...created.get(key) ?? [], change.value.id]);\n }\n for (const [key, ids] of created) {\n const conversations = [...node(key).conversations, ...ids].sort((a, b) => a - b);\n ops.push([\"s\", [\"tasks\", key, \"conversations\"], conversations]);\n }\n if (ops.length === 0)\n return;\n mount.value = applyImmutable(mount.value, ops);\n const frameContext = withoutAbortSignal(context2);\n for (const observer of [...mount.observers])\n observer.advance(mount.value, ops, frameContext);\n }\n function nodeOf2(record, conversations) {\n return {\n id: record.id,\n kind: record.kind,\n conversationId: record.conversationId,\n ...record.owner === void 0 ? {} : { owner: record.owner },\n background: record.background,\n abortRequested: record.abortRequested,\n state: stateOf(record),\n conversations\n };\n }\n function stateOf(record) {\n const state2 = record.state;\n switch (state2.status) {\n case \"pending\":\n case \"running\":\n return { status: state2.status, phase: phaseOf(state2.checkpoint) };\n case \"waiting\":\n return { status: \"waiting\", phase: phaseOf(state2.checkpoint), on: [...state2.on], policy: state2.policy };\n // Terminal records never reach here: they leave the graph.\n case \"completing\":\n case \"terminal\":\n return { status: \"completing\", outcome: state2.outcome.status };\n }\n }\n function phaseOf(checkpoint) {\n return checkpoint.phase;\n }\n\n // node_modules/@earendil-works/pi-durable/dist/harness/harness.js\n var SCAN_PAGE_SIZE5 = 256;\n var ConversationImpl = class {\n id;\n #host;\n constructor(id, host) {\n this.id = id;\n this.#host = host;\n }\n agent(context2) {\n return this.#host.harness.resolveAgent(this.id, void 0, context2);\n }\n configure(change, context2) {\n return this.#host.harness.commitWith((tx) => configure(tx, this.id, change), context2);\n }\n submit(submission, context2) {\n return this.#host.submissions.submit(this.id, submission, context2);\n }\n compact(instructions, context2) {\n this.#host.tasks.resume();\n const input = { reason: \"manual\", ...instructions === void 0 ? {} : { instructions } };\n return this.#host.harness.commitWith((tx) => createCompaction(tx, this.id, input), context2);\n }\n async reset(handoff, context2) {\n const model = handoff === void 0 ? {} : { model: [{ role: \"user\", content: handoff, timestamp: this.#host.now() }] };\n const entry = { kind: ResetEntry.kind, head: \"self\", ...model };\n await this.#host.submissions.submit(this.id, { type: \"write\", entry }, context2);\n }\n commit(change, context2) {\n return this.#host.harness.commitWith(change, context2, { conversationId: this.id });\n }\n context(context2, options) {\n return readContext(this.#host.harness, this.#host.storage, this.id, context2, options?.at);\n }\n entries(query, limit, cursor, context2) {\n const bounded = {\n conversationId: this.id,\n ...query.minEntryId === void 0 ? {} : { minEntryId: query.minEntryId },\n ...query.maxEntryId === void 0 ? {} : { maxEntryId: query.maxEntryId },\n ...query.order === void 0 ? {} : { order: query.order }\n };\n return this.#host.harness.readOnLine(() => this.#host.storage.scanEntries(bounded, limit, cursor, context2));\n }\n fork(at, options, context2) {\n return this.#host.create({ kind: \"fork\", parentId: this.id, at, ownership: options.ownership }, options, context2);\n }\n abort(context2, options) {\n this.#host.tasks.resume();\n return this.#host.tasks.abortConversation(this.id, options?.background === true, context2);\n }\n waitForIdle(context2) {\n this.#host.tasks.resume();\n return this.#host.tasks.waitForIdle(this.id, context2);\n }\n viewState(context2) {\n return this.#host.views.state(this.id, context2);\n }\n watch(context2) {\n return this.#host.views.watch(this.id, context2);\n }\n };\n var HarnessImpl = class extends SessionImpl {\n #storage;\n #options;\n #report;\n #host;\n #tasks;\n #submissions;\n #taskGraph;\n #closed = false;\n constructor(storage, options, context2) {\n super(storage, options.now);\n this.#storage = storage;\n this.#options = options;\n this.#report = options.onReport ?? (() => {\n });\n const now = options.now ?? Date.now;\n const settings2 = () => resolveSettings(options.settings);\n this.#tasks = new TaskScheduler({\n session: this,\n storage,\n registry: options.registry,\n models: options.models,\n agent: (id, snapshot, callContext) => this.resolveAgent(id, snapshot, callContext),\n settings: settings2,\n env: (id, callContext) => this.buildEnv(id, callContext),\n now,\n report: this.#report,\n settleOutcome: settleSchedulerOutcome,\n withdrawInputs: withdrawQueuedInputs,\n conversation: async (id, binding, callContext) => {\n const record = await this.readOnLine(() => storage.conversation(id, callContext));\n return record === void 0 ? void 0 : boundConversation(id, binding, this.#submissions, this.#tasks);\n },\n context: withoutAbortSignal(context2)\n });\n this.#submissions = new Submissions(this, storage, now, settings2, () => this.#tasks.resume());\n this.#taskGraph = new TaskGraphView(this, storage);\n this.#host = {\n harness: this,\n storage,\n tasks: this.#tasks,\n submissions: this.#submissions,\n views: new ConversationViews(this, storage),\n now,\n create: (target, createOptions, context3) => this.#create(target, createOptions, context3)\n };\n }\n /** Resolve a conversation's committed `pi.agent` against `snapshot`, or the current one, and the current settings. */\n async resolveAgent(id, snapshot, context2) {\n const registry2 = snapshot ?? this.#options.registry.snapshot();\n const state2 = await this.snapshot(AgentDoc, id, context2);\n return resolveAgent(state2, registry2, resolveSettings(this.#options.settings), this.#report);\n }\n /** Build a conversation's environment from its current `cwd`; `undefined` without an `env` option. */\n async buildEnv(id, context2) {\n const build = this.#options.env;\n if (build === void 0)\n return void 0;\n const cwd = (await this.snapshot(AgentDoc, id, context2))?.cwd;\n return build({ conversationId: id, ...cwd === void 0 ? {} : { cwd }, read: this }, context2);\n }\n /** Reconcile surviving `running` tasks to `pending`; part of open. */\n openTasks(context2) {\n return this.#tasks.open(context2);\n }\n resume() {\n this.#assertOpen();\n this.#tasks.resume();\n }\n getTask(id, context2) {\n return this.readOnLine(() => this.#storage.task(id, context2));\n }\n inspect(context2) {\n return this.readOnLine(async () => {\n const { scheduling, tasks } = await this.#tasks.inspect(this.#options.registry.snapshot());\n const scan = (status) => scanAll((cursor) => this.#storage.scanSubmissions({ status }, SCAN_PAGE_SIZE5, cursor, context2));\n const submissions = [...await scan(\"queued\"), ...await scan(\"placed\")].sort((a, b) => a.id - b.id);\n return { scheduling, tasks, submissions };\n });\n }\n submission(id, context2) {\n return this.#submissions.get(id, context2);\n }\n abortSubmission(id, context2, conversationId) {\n return this.#submissions.abort(id, context2, conversationId);\n }\n abortTask(id, context2) {\n return this.#tasks.abort(id, context2);\n }\n waitForTask(id, context2) {\n this.#tasks.resume();\n return this.#tasks.waitForTask(id, context2);\n }\n waitForIdle(context2) {\n this.#tasks.resume();\n return this.#tasks.waitForIdle(void 0, context2);\n }\n /** Sum every conversation's committed `pi.usage`. Each document is read at its own point; totals only grow. */\n async usage(context2) {\n const conversations = await this.readOnLine(() => scanAll((cursor) => this.#storage.scanConversations({}, SCAN_PAGE_SIZE5, cursor, context2)));\n const total = UsageDoc.definition.initial();\n for (const { id } of conversations) {\n const state2 = await this.snapshot(UsageDoc, id, context2);\n if (state2 !== void 0)\n addUsageState(total, state2);\n }\n return total;\n }\n taskGraph(context2) {\n return this.#taskGraph.state(context2);\n }\n watchTaskGraph(context2) {\n return this.#taskGraph.watch(context2);\n }\n root(context2, options) {\n return this.#create({ kind: \"root\" }, options ?? {}, context2);\n }\n async conversation(id, context2) {\n this.#assertOpen();\n const record = await this.readOnLine(() => this.#storage.conversation(id, context2));\n return record === void 0 ? void 0 : new ConversationImpl(record.id, this.#host);\n }\n createConversation(options, context2) {\n return this.#create({ kind: \"independent\", ownership: options.ownership }, options, context2);\n }\n close(context2) {\n this.#closed = true;\n return super.close(context2);\n }\n /** Join task invocations after admission is sealed and before Storage closes; writes no task outcome. */\n beforeClose() {\n return this.#tasks.join();\n }\n async #create(target, options, context2) {\n this.#assertOpen();\n const id = await this.commitWith(async (tx) => {\n if (target.kind === \"root\" && await tx.conversation(ROOT_CONVERSATION_ID) !== void 0) {\n return ROOT_CONVERSATION_ID;\n }\n const record = target.kind === \"root\" ? await tx.createRootConversation() : target.kind === \"fork\" ? await tx.forkConversation(target.parentId, target.at, { ownership: target.ownership }) : await tx.createConversation({ ownership: target.ownership });\n if (options.agent !== void 0)\n await configure(tx, record.id, options.agent);\n if (options.init !== void 0)\n await options.init(tx, record.id);\n return record.id;\n }, context2);\n return new ConversationImpl(id, this.#host);\n }\n /**\n * The built-in creation hook, in every commit that creates or forks a conversation: empty `pi.live`, `pi.inbox`, and\n * `pi.usage`, a fresh `pi.provider`, the conversation's `pi.agent` (see `createAgent()`), then\n * `HarnessOptions.conversationCreated`.\n */\n async conversationCreated(tx, record) {\n await tx.doc(LiveDoc, record.id);\n await tx.doc(InboxDoc, record.id);\n await tx.doc(UsageDoc, record.id);\n await tx.doc(ProviderDoc, record.id);\n await createAgent(tx, record);\n await this.#options.conversationCreated?.(tx, record);\n }\n #assertOpen() {\n if (this.#closed)\n throw new Error(\"Harness is closed\");\n }\n };\n function boundConversation(id, binding, submissions, tasks) {\n const bind = (context2) => withAbortSignal(binding.signal, context2);\n const bound = (operation) => {\n return async (context2) => {\n binding.check();\n return operation(bind(context2));\n };\n };\n return {\n id,\n submit: async (draft, context2) => {\n binding.check();\n const submission = await submissions.submit(id, draft, bind(context2));\n return {\n id: submission.id,\n status: bound((callContext) => submission.status(callContext)),\n wait: bound((callContext) => submission.wait(callContext)),\n abort: bound((callContext) => submission.abort(callContext))\n };\n },\n abort: async (context2, options) => {\n binding.check();\n return tasks.abortConversation(id, options?.background === true, bind(context2));\n },\n waitForIdle: bound((callContext) => tasks.waitForIdle(id, callContext))\n };\n }\n var Harness = {\n /** Open a Harness over storage. The registry may keep changing while the Harness runs. */\n async open(storage, options, context2) {\n context2.abortSignal?.throwIfAborted();\n const snapshot = options.registry.snapshot();\n const missing = BUILTIN_TASKS.filter((task) => snapshot.task(task.definition.name) === void 0);\n if (missing.length > 0) {\n const names3 = missing.map((task) => task.definition.name).join(\", \");\n throw new Error(`Registry lacks built-in tasks ${names3}; create it with createRegistry()`);\n }\n const harness2 = new HarnessImpl(storage, options, context2);\n try {\n await harness2.openTasks(context2);\n } catch (error) {\n await harness2.close(withoutAbortSignal(context2)).catch((closeError) => options.onReport?.(closeError));\n throw error;\n }\n return harness2;\n }\n };\n\n // node_modules/@earendil-works/pi-durable/dist/storage/scan.js\n function scanStart(requested, cursor, fallback) {\n if (requested !== void 0 && requested !== \"ascending\" && requested !== \"descending\") {\n throw new TypeError(`Invalid scan order: ${String(requested)}`);\n }\n if (cursor === void 0)\n return { order: requested ?? fallback, after: void 0 };\n const { after, order: stored } = cursor;\n if (typeof after !== \"number\" || !Number.isSafeInteger(after))\n throw new TypeError(\"Invalid storage cursor\");\n if (stored !== void 0 && stored !== \"ascending\" && stored !== \"descending\") {\n throw new TypeError(\"Invalid storage cursor\");\n }\n const order = stored ?? fallback;\n if (requested !== void 0 && requested !== order) {\n throw new TypeError(`The cursor continues a ${order} scan; the query asks for ${requested}`);\n }\n return { order, after };\n }\n function nextCursor(id, order) {\n return { after: id, order };\n }\n\n // node_modules/@earendil-works/pi-durable/dist/storage/memory.js\n function* documentDeltaBatches(id, version, revisions, start) {\n for (let index3 = start; index3 < revisions.length; index3++) {\n const revision = revisions[index3];\n if (revision.kind !== \"delta\" || revision.version !== version) {\n throw new Error(`Document ${id} crosses a stored version boundary without a base`);\n }\n yield revision.ops;\n }\n }\n var clone = (value) => {\n if (value === null || typeof value !== \"object\")\n return value;\n if (Array.isArray(value))\n return value.map((item) => clone(item));\n const source = value;\n const nullPrototype = Object.getPrototypeOf(value) === null;\n const result = nullPrototype ? /* @__PURE__ */ Object.create(null) : {};\n for (const key of Object.keys(source)) {\n const copied = clone(source[key]);\n if (!nullPrototype && key in result) {\n Object.defineProperty(result, key, {\n value: copied,\n writable: true,\n enumerable: true,\n configurable: true\n });\n } else {\n result[key] = copied;\n }\n }\n return result;\n };\n var freeze = (value) => {\n if (value === null || typeof value !== \"object\" || Object.isFrozen(value))\n return value;\n for (const child of Object.values(value))\n freeze(child);\n return Object.freeze(value);\n };\n var cursorId = (cursor) => {\n const after = cursor?.after;\n if (after === void 0)\n return void 0;\n if (typeof after !== \"number\" || !Number.isSafeInteger(after))\n throw new TypeError(\"Invalid storage cursor\");\n return idFromNumber(after);\n };\n var lowerBound = (ids, target) => {\n let low = 0;\n let high = ids.length;\n while (low < high) {\n const middle = low + high >>> 1;\n if (ids[middle] < target)\n low = middle + 1;\n else\n high = middle;\n }\n return low;\n };\n var upperBound = (ids, target) => {\n let low = 0;\n let high = ids.length;\n while (low < high) {\n const middle = low + high >>> 1;\n if (ids[middle] <= target)\n low = middle + 1;\n else\n high = middle;\n }\n return low;\n };\n var insertSorted = (ids, id) => {\n if (ids.length === 0 || ids[ids.length - 1] < id)\n ids.push(id);\n else\n ids.splice(lowerBound(ids, id), 0, id);\n };\n var removeSorted = (ids, id) => {\n const index3 = lowerBound(ids, id);\n if (ids[index3] === id)\n ids.splice(index3, 1);\n };\n var insertMapId = (index3, key, id) => {\n let ids = index3.get(key);\n if (ids === void 0) {\n ids = [];\n index3.set(key, ids);\n }\n insertSorted(ids, id);\n };\n var scopeKey = (scope) => {\n switch (scope.kind) {\n case \"session\":\n return JSON.stringify([\"session\"]);\n case \"conversation\":\n return JSON.stringify([\"conversation\", scope.conversationId]);\n case \"task\":\n return JSON.stringify([\"task\", scope.taskId]);\n }\n };\n var addressKey = (address) => JSON.stringify([\n address.kind,\n scopeKey(address.scope),\n address.key === void 0 ? [\"singleton\"] : [\"family\", address.key]\n ]);\n var recordAddressKey = (record) => addressKey({ kind: record.kind, scope: record.scope, key: record.key });\n var isAliveAt = (record, at) => {\n if (at === \"current\")\n return record.retiredAt === void 0;\n return record.createdAt <= at && (record.retiredAt === void 0 || at < record.retiredAt);\n };\n var isCurrentOnly = (record) => record.scope.kind !== \"conversation\" || record.history === \"latest\";\n var tableContaining = (state2, id) => state2.recordTypes.get(id);\n var page = (values, limit, order = \"ascending\") => {\n const items = values.slice(0, limit);\n if (values.length <= limit)\n return { items: clone(items) };\n return { items: clone(items), next: nextCursor(items.at(-1).id, order) };\n };\n function* scanIndexes(ids, start) {\n if (start.order === \"ascending\") {\n const first = start.after === void 0 ? 0 : upperBound(ids, start.after);\n for (let index3 = first; index3 < ids.length; index3++)\n yield index3;\n } else {\n const end = start.after === void 0 ? ids.length : lowerBound(ids, start.after);\n for (let index3 = end - 1; index3 >= 0; index3--)\n yield index3;\n }\n }\n var MemoryStorage = class {\n state = {\n recordTypes: /* @__PURE__ */ new Map(),\n conversations: /* @__PURE__ */ new Map(),\n conversationIds: [],\n conversationIdsByOwnerConversation: /* @__PURE__ */ new Map(),\n conversationIdsByOwnerTask: /* @__PURE__ */ new Map(),\n entries: /* @__PURE__ */ new Map(),\n entryIds: /* @__PURE__ */ new Map(),\n headEntryIds: /* @__PURE__ */ new Map(),\n entryCommitSeqs: /* @__PURE__ */ new Map(),\n tasks: /* @__PURE__ */ new Map(),\n taskIds: [],\n taskIdsByStatus: { pending: [], running: [], waiting: [], completing: [], terminal: [] },\n submissions: /* @__PURE__ */ new Map(),\n submissionIds: [],\n submissionIdsByStatus: { queued: [], placed: [], done: [], unanswered: [] },\n submissionIdsByRequest: /* @__PURE__ */ new Map(),\n documents: /* @__PURE__ */ new Map(),\n documentAddresses: /* @__PURE__ */ new Map(),\n documentIdsByScope: /* @__PURE__ */ new Map()\n };\n nextId = 2;\n nextSeq = 1;\n closed = false;\n async commit(writes, _context) {\n return this.prepareCommit(writes).apply();\n }\n /** Validate and detach one commit without changing observable state. */\n prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) {\n this.assertOpen();\n if (!Number.isSafeInteger(seq) || seq < this.nextSeq) {\n throw new Error(`Commit sequence ${seq} does not strictly increase`);\n }\n const detachedWrites = freeze(this.resolveDocumentCopies(writes.map((write) => clone(write))));\n this.checkGlobalIds(detachedWrites);\n const documentActions = this.prepareDocumentActions(detachedWrites);\n this.checkDocumentActions(documentActions);\n let applied = false;\n return {\n seq,\n writes: detachedWrites,\n apply: () => {\n if (!applied) {\n applied = true;\n this.applyPreparedCommit(detachedWrites, documentActions, seq);\n }\n return seq;\n }\n };\n }\n resolveDocumentCopies(writes) {\n if (!writes.some((write) => write.type === \"document.copy\"))\n return writes;\n const changedDocumentIds = /* @__PURE__ */ new Set();\n for (const write of writes) {\n if (write.type === \"document.create\" || write.type === \"document.copy\") {\n changedDocumentIds.add(write.record.id);\n } else if (write.type === \"document.change\" || write.type === \"document.retire\") {\n changedDocumentIds.add(write.id);\n }\n }\n return writes.map((write) => {\n if (write.type !== \"document.copy\")\n return write;\n try {\n if (changedDocumentIds.has(write.source.id)) {\n throw new Error(`Fork source document ${write.source.id} is changed in the copy batch`);\n }\n const stored = this.materializeDocument(write.source.id, write.source.at);\n if (stored === void 0)\n throw new Error(`Fork source document ${write.source.id} cannot be read`);\n if (stored.record.scope.kind !== \"conversation\" || write.record.scope.kind !== \"conversation\" || stored.record.kind !== write.record.kind || stored.record.key !== write.record.key || stored.record.history !== write.record.history || stored.record.fork !== write.record.fork) {\n throw new Error(`Fork source document ${write.source.id} does not match the copied record`);\n }\n return {\n type: \"document.create\",\n record: write.record,\n content: { kind: \"base\", version: stored.version, value: stored.value }\n };\n } catch (error) {\n if (error instanceof StorageRejected)\n throw error;\n throw new StorageRejected(`Document copy ${write.record.id} was rejected`, { cause: error });\n }\n });\n }\n applyPreparedCommit(prepared, documentActions, seq) {\n for (const write of prepared) {\n switch (write.type) {\n case \"conversation\": {\n this.state.recordTypes.set(write.value.id, \"conversation\");\n this.state.conversations.set(write.value.id, write.value);\n insertSorted(this.state.conversationIds, write.value.id);\n const owner = write.value.owner;\n if (owner !== void 0) {\n insertMapId(this.state.conversationIdsByOwnerConversation, owner.conversationId, write.value.id);\n insertMapId(this.state.conversationIdsByOwnerTask, owner.taskId, write.value.id);\n }\n this.nextId = Math.max(this.nextId, write.value.id + 1);\n break;\n }\n case \"entry\": {\n this.state.recordTypes.set(write.value.id, \"entry\");\n this.state.entries.set(write.value.id, write.value);\n this.state.entryCommitSeqs.set(write.value.id, seq);\n let ids = this.state.entryIds.get(write.value.conversationId);\n if (ids === void 0) {\n ids = [];\n this.state.entryIds.set(write.value.conversationId, ids);\n }\n insertSorted(ids, write.value.id);\n if (write.value.head !== void 0) {\n let headIds = this.state.headEntryIds.get(write.value.conversationId);\n if (headIds === void 0) {\n headIds = [];\n this.state.headEntryIds.set(write.value.conversationId, headIds);\n }\n insertSorted(headIds, write.value.id);\n }\n this.nextId = Math.max(this.nextId, write.value.id + 1);\n break;\n }\n case \"task\": {\n this.state.recordTypes.set(write.value.id, \"task\");\n const previous = this.state.tasks.get(write.value.id);\n if (previous === void 0) {\n insertSorted(this.state.taskIds, write.value.id);\n insertSorted(this.state.taskIdsByStatus[write.value.state.status], write.value.id);\n } else if (previous.state.status !== write.value.state.status) {\n removeSorted(this.state.taskIdsByStatus[previous.state.status], write.value.id);\n insertSorted(this.state.taskIdsByStatus[write.value.state.status], write.value.id);\n }\n this.state.tasks.set(write.value.id, write.value);\n this.nextId = Math.max(this.nextId, write.value.id + 1);\n break;\n }\n case \"submission\": {\n this.state.recordTypes.set(write.value.id, \"submission\");\n const previous = this.state.submissions.get(write.value.id);\n if (previous === void 0) {\n insertSorted(this.state.submissionIds, write.value.id);\n insertSorted(this.state.submissionIdsByStatus[write.value.status], write.value.id);\n } else if (previous.status !== write.value.status) {\n removeSorted(this.state.submissionIdsByStatus[previous.status], write.value.id);\n insertSorted(this.state.submissionIdsByStatus[write.value.status], write.value.id);\n }\n if (previous?.requestId !== void 0) {\n const previousRequests = this.state.submissionIdsByRequest.get(previous.conversationId);\n if (previousRequests?.get(previous.requestId) === write.value.id) {\n previousRequests.delete(previous.requestId);\n if (previousRequests.size === 0)\n this.state.submissionIdsByRequest.delete(previous.conversationId);\n }\n }\n this.state.submissions.set(write.value.id, write.value);\n if (write.value.requestId !== void 0) {\n let requests = this.state.submissionIdsByRequest.get(write.value.conversationId);\n if (requests === void 0) {\n requests = /* @__PURE__ */ new Map();\n this.state.submissionIdsByRequest.set(write.value.conversationId, requests);\n }\n requests.set(write.value.requestId, write.value.id);\n }\n this.nextId = Math.max(this.nextId, write.value.id + 1);\n break;\n }\n case \"document.copy\":\n throw new Error(\"Prepared document copy was not resolved\");\n case \"document.create\":\n case \"document.change\":\n case \"document.retire\":\n break;\n }\n }\n this.applyDocumentActions(documentActions, seq);\n this.nextSeq = seq + 1;\n return seq;\n }\n async mintId() {\n this.assertOpen();\n if (!Number.isSafeInteger(this.nextId))\n throw new Error(\"ID space is exhausted\");\n return idFromNumber(this.nextId++);\n }\n async conversation(id, _context) {\n this.assertOpen();\n const value = this.state.conversations.get(id);\n return value === void 0 ? void 0 : clone(value);\n }\n async scanConversations(query, limit, cursor, _context) {\n this.assertOpen();\n const ids = query.ownerTaskId !== void 0 ? this.state.conversationIdsByOwnerTask.get(query.ownerTaskId) ?? [] : query.ownerConversationId !== void 0 ? this.state.conversationIdsByOwnerConversation.get(query.ownerConversationId) ?? [] : this.state.conversationIds;\n const start = scanStart(query.order, cursor, \"ascending\");\n const values = [];\n for (const index3 of scanIndexes(ids, start)) {\n if (values.length > limit)\n break;\n const value = this.state.conversations.get(ids[index3]);\n if (query.ownerConversationId !== void 0 && value.owner?.conversationId !== query.ownerConversationId) {\n continue;\n }\n values.push(value);\n }\n return page(values, limit, start.order);\n }\n async entry(idOrConversationId, idOrContext, context2) {\n this.assertOpen();\n if (context2 === void 0) {\n const id2 = idFromNumber(idOrConversationId);\n const entry2 = this.state.entries.get(id2);\n if (entry2 === void 0)\n return void 0;\n return { entry: clone(entry2), commitSeq: this.state.entryCommitSeqs.get(id2) };\n }\n if (typeof idOrContext !== \"number\")\n throw new TypeError(\"Storage.entry() requires an entry ID\");\n const conversationId = idFromNumber(idOrConversationId);\n const id = idFromNumber(idOrContext);\n const entry = this.visibleEntries(conversationId, id, id).next().value;\n if (entry === void 0)\n return void 0;\n return { entry: clone(entry), commitSeq: this.state.entryCommitSeqs.get(id) };\n }\n async findLatestHeadMarker(conversationId, atOrBeforeEntryId, _context) {\n this.assertOpen();\n if (!this.state.conversations.has(conversationId)) {\n throw new Error(`Unknown conversation: ${conversationId}`);\n }\n let currentId = conversationId;\n let upperEntryId = atOrBeforeEntryId ?? Number.POSITIVE_INFINITY;\n while (true) {\n const ids = this.state.headEntryIds.get(currentId) ?? [];\n const index3 = upperBound(ids, upperEntryId) - 1;\n if (index3 >= 0) {\n const entry = this.state.entries.get(ids[index3]);\n return clone({ ...entry, head: entry.head });\n }\n const conversation2 = this.state.conversations.get(currentId);\n if (conversation2.parent === void 0)\n return void 0;\n upperEntryId = Math.min(upperEntryId, conversation2.parent.at);\n currentId = conversation2.parent.conversationId;\n }\n }\n async scanEntries(query, limit, cursor, _context) {\n this.assertOpen();\n const { order, after } = scanStart(query.order, cursor, \"descending\");\n let minEntryId = query.minEntryId;\n let maxEntryId = query.maxEntryId;\n if (after !== void 0 && order === \"descending\")\n maxEntryId = Math.min(maxEntryId ?? after, after - 1);\n if (after !== void 0 && order === \"ascending\")\n minEntryId = Math.max(minEntryId ?? after, after + 1);\n const visible = [];\n const entries = order === \"descending\" ? this.visibleEntries(query.conversationId, minEntryId, maxEntryId) : this.visibleEntriesAscending(query.conversationId, minEntryId, maxEntryId);\n for (const entry of entries) {\n visible.push(entry);\n if (visible.length > limit)\n break;\n }\n return page(visible, limit, order);\n }\n async task(id, _context) {\n this.assertOpen();\n const value = this.state.tasks.get(id);\n return value === void 0 ? void 0 : clone(value);\n }\n async scanTasks(query, limit, cursor, _context) {\n this.assertOpen();\n const start = scanStart(query.order, cursor, \"ascending\");\n const ids = query.status === void 0 ? this.state.taskIds : this.state.taskIdsByStatus[query.status];\n const values = [];\n for (const index3 of scanIndexes(ids, start)) {\n if (values.length > limit)\n break;\n const value = this.state.tasks.get(ids[index3]);\n if (query.conversationId !== void 0 && value.conversationId !== query.conversationId)\n continue;\n if (query.kind !== void 0 && value.kind !== query.kind)\n continue;\n if (query.abortRequested !== void 0 && value.abortRequested !== query.abortRequested)\n continue;\n if (query.background !== void 0 && value.background !== query.background)\n continue;\n values.push(value);\n }\n return page(values, limit, start.order);\n }\n async submission(id, _context) {\n this.assertOpen();\n const value = this.state.submissions.get(id);\n return value === void 0 ? void 0 : clone(value);\n }\n async scanSubmissions(query, limit, cursor, _context) {\n this.assertOpen();\n const start = scanStart(query.order, cursor, \"ascending\");\n const ids = query.status === void 0 ? this.state.submissionIds : this.state.submissionIdsByStatus[query.status];\n const values = [];\n for (const index3 of scanIndexes(ids, start)) {\n if (values.length > limit)\n break;\n const value = this.state.submissions.get(ids[index3]);\n if (query.conversationId !== void 0 && value.conversationId !== query.conversationId)\n continue;\n values.push(value);\n }\n return page(values, limit, start.order);\n }\n async submissionByRequest(conversationId, requestId, _context) {\n this.assertOpen();\n const id = this.state.submissionIdsByRequest.get(conversationId)?.get(requestId);\n if (id === void 0)\n return void 0;\n return clone(this.state.submissions.get(id));\n }\n async findDocument(address, at, _context) {\n this.assertOpen();\n const index3 = this.state.documentAddresses.get(addressKey(address));\n if (at === \"current\") {\n return index3?.currentId === void 0 ? void 0 : clone(this.state.documents.get(index3.currentId).record);\n }\n for (const id of index3?.ids ?? []) {\n const record = this.state.documents.get(id).record;\n if (isAliveAt(record, at))\n return clone(record);\n }\n return void 0;\n }\n async document(id, at, _context) {\n this.assertOpen();\n const stored = this.materializeDocument(id, at);\n return stored === void 0 ? void 0 : {\n record: clone(stored.record),\n version: stored.version,\n value: clone(stored.value),\n deltasSinceBase: stored.deltasSinceBase\n };\n }\n async scanDocuments(query, limit, cursor, _context) {\n this.assertOpen();\n const ids = this.state.documentIdsByScope.get(scopeKey(query.scope)) ?? [];\n const after = cursorId(cursor);\n const start = after === void 0 ? 0 : upperBound(ids, after);\n const values = [];\n for (let index3 = start; index3 < ids.length && values.length <= limit; index3++) {\n const record = this.state.documents.get(ids[index3]).record;\n if (query.kind !== void 0 && record.kind !== query.kind)\n continue;\n if (isAliveAt(record, query.at))\n values.push(record);\n }\n return page(values, limit);\n }\n async close(_context) {\n this.closed = true;\n }\n materializeDocument(id, at) {\n const stored = this.state.documents.get(id);\n if (stored === void 0)\n return void 0;\n if (at !== \"current\" && isCurrentOnly(stored.record)) {\n throw new Error(`Document ${id} does not retain historical content`);\n }\n if (!isAliveAt(stored.record, at))\n return void 0;\n const revisions = at === \"current\" ? stored.revisions : stored.revisions.filter((revision) => revision.seq <= at);\n let baseIndex = revisions.length - 1;\n while (baseIndex >= 0 && revisions[baseIndex].kind !== \"base\")\n baseIndex--;\n const base = revisions[baseIndex];\n if (base?.kind !== \"base\")\n throw new Error(`Document ${id} is missing a required base`);\n const value = applyImmutableBatches(base.value, documentDeltaBatches(id, base.version, revisions, baseIndex + 1));\n return { record: stored.record, version: base.version, value, deltasSinceBase: revisions.length - baseIndex - 1 };\n }\n *visibleEntries(conversationId, minEntryId = Number.NEGATIVE_INFINITY, maxEntryId = Number.POSITIVE_INFINITY) {\n if (!this.state.conversations.has(conversationId)) {\n throw new Error(`Unknown conversation: ${conversationId}`);\n }\n let currentId = conversationId;\n let upperEntryId = maxEntryId;\n while (true) {\n const ids = this.state.entryIds.get(currentId) ?? [];\n for (let index3 = upperBound(ids, upperEntryId) - 1; index3 >= 0; index3--) {\n const id = ids[index3];\n if (id < minEntryId)\n break;\n yield this.state.entries.get(id);\n }\n const conversation2 = this.state.conversations.get(currentId);\n if (conversation2.parent === void 0)\n break;\n upperEntryId = Math.min(upperEntryId, conversation2.parent.at);\n if (upperEntryId < minEntryId)\n break;\n currentId = conversation2.parent.conversationId;\n }\n }\n /** Visible entries oldest first: the fork chain's segments from the root conversation forward. */\n *visibleEntriesAscending(conversationId, minEntryId = Number.NEGATIVE_INFINITY, maxEntryId = Number.POSITIVE_INFINITY) {\n if (!this.state.conversations.has(conversationId)) {\n throw new Error(`Unknown conversation: ${conversationId}`);\n }\n const segments = [];\n let currentId = conversationId;\n let upperEntryId = maxEntryId;\n while (true) {\n segments.push({ conversationId: currentId, upper: upperEntryId });\n const conversation2 = this.state.conversations.get(currentId);\n if (conversation2.parent === void 0)\n break;\n upperEntryId = Math.min(upperEntryId, conversation2.parent.at);\n if (upperEntryId < minEntryId)\n break;\n currentId = conversation2.parent.conversationId;\n }\n for (const segment of segments.reverse()) {\n const ids = this.state.entryIds.get(segment.conversationId) ?? [];\n for (let index3 = lowerBound(ids, minEntryId); index3 < ids.length; index3++) {\n const id = ids[index3];\n if (id > segment.upper)\n break;\n yield this.state.entries.get(id);\n }\n }\n }\n checkGlobalIds(writes) {\n const claimed = /* @__PURE__ */ new Map();\n for (const write of writes) {\n if (write.type === \"document.change\" || write.type === \"document.retire\")\n continue;\n const document = write.type === \"document.create\" || write.type === \"document.copy\";\n const table = document ? \"document\" : write.type;\n const id = document ? write.record.id : write.value.id;\n const existing = tableContaining(this.state, id);\n const earlier = claimed.get(id);\n if (table === \"conversation\" || table === \"entry\" || table === \"document\") {\n if (existing !== void 0)\n throw new Error(`ID ${id} already belongs to ${existing}`);\n if (earlier !== void 0)\n throw new Error(`ID ${id} is written more than once`);\n } else {\n if (existing !== void 0 && existing !== table) {\n throw new Error(`ID ${id} already belongs to ${existing}`);\n }\n if (earlier !== void 0 && earlier !== table)\n throw new Error(`ID ${id} is written as two record types`);\n }\n claimed.set(id, table);\n }\n }\n prepareDocumentActions(writes) {\n const actions = /* @__PURE__ */ new Map();\n for (const write of writes) {\n if (write.type !== \"document.create\" && write.type !== \"document.change\" && write.type !== \"document.retire\") {\n continue;\n }\n const id = write.type === \"document.create\" ? write.record.id : write.id;\n let action = actions.get(id);\n if (action === void 0) {\n action = { retire: false };\n actions.set(id, action);\n }\n switch (write.type) {\n case \"document.create\":\n if (action.create !== void 0 || action.content !== void 0) {\n throw new Error(`Document ${id} has more than one content command`);\n }\n action.create = write.record;\n action.content = write.content;\n break;\n case \"document.change\":\n if (action.content !== void 0)\n throw new Error(`Document ${id} has more than one content command`);\n action.content = write.content;\n break;\n case \"document.retire\":\n if (action.retire)\n throw new Error(`Document ${id} is retired more than once`);\n action.retire = true;\n break;\n }\n }\n return actions;\n }\n checkDocumentActions(actions) {\n const liveCounts = /* @__PURE__ */ new Map();\n for (const [id, action] of actions) {\n const existing = this.state.documents.get(id);\n if (action.create === void 0 && existing === void 0)\n throw new Error(`Unknown document: ${id}`);\n if (action.create !== void 0 && existing !== void 0)\n throw new Error(`Document ${id} already exists`);\n if (existing?.record.retiredAt !== void 0)\n throw new Error(`Document ${id} is retired`);\n const previous = existing?.revisions.at(-1);\n if (action.content?.kind === \"delta\") {\n if (previous === void 0)\n throw new Error(`Document ${id} delta has no base`);\n if (previous.version !== action.content.version) {\n throw new Error(`Document ${id} version transition requires a base`);\n }\n }\n const key = action.create === void 0 ? recordAddressKey(existing.record) : recordAddressKey(action.create);\n const currentId = this.state.documentAddresses.get(key)?.currentId;\n let live = liveCounts.get(key);\n if (live === void 0)\n live = currentId === void 0 ? 0 : 1;\n if (action.retire && currentId === id)\n live--;\n if (action.create !== void 0 && !action.retire)\n live++;\n liveCounts.set(key, live);\n }\n for (const live of liveCounts.values()) {\n if (live > 1)\n throw new Error(`Document address already has a current incarnation`);\n }\n }\n applyDocumentActions(actions, seq) {\n for (const [id, action] of actions) {\n let stored = this.state.documents.get(id);\n if (action.create !== void 0) {\n const record = {\n ...action.create,\n createdAt: seq,\n ...action.retire ? { retiredAt: seq } : {}\n };\n stored = { record, revisions: [{ ...action.content, seq }] };\n this.state.recordTypes.set(id, \"document\");\n this.state.documents.set(id, stored);\n const key = recordAddressKey(record);\n let address = this.state.documentAddresses.get(key);\n if (address === void 0) {\n address = { ids: [] };\n this.state.documentAddresses.set(key, address);\n }\n insertSorted(address.ids, id);\n let scopeIds = this.state.documentIdsByScope.get(scopeKey(record.scope));\n if (scopeIds === void 0) {\n scopeIds = [];\n this.state.documentIdsByScope.set(scopeKey(record.scope), scopeIds);\n }\n insertSorted(scopeIds, id);\n this.nextId = Math.max(this.nextId, id + 1);\n } else if (action.content !== void 0) {\n const revision = { ...action.content, seq };\n if (revision.kind === \"base\" && isCurrentOnly(stored.record))\n stored.revisions = [revision];\n else\n stored.revisions.push(revision);\n }\n if (action.retire && action.create === void 0)\n stored.record = { ...stored.record, retiredAt: seq };\n if (action.retire && isCurrentOnly(stored.record))\n stored.revisions = [];\n if (action.create !== void 0 || action.retire) {\n const address = this.state.documentAddresses.get(recordAddressKey(stored.record));\n if (action.retire && address.currentId === id)\n delete address.currentId;\n if (action.create !== void 0 && !action.retire)\n address.currentId = id;\n }\n }\n }\n assertOpen() {\n if (this.closed)\n throw new Error(\"MemoryStorage is closed\");\n }\n };\n\n // node_modules/typebox/build/typebox.mjs\n var typebox_exports = {};\n __export(typebox_exports, {\n Any: () => Any,\n Array: () => _Array_,\n BigInt: () => BigInt2,\n Boolean: () => Boolean2,\n Call: () => Call2,\n Capitalize: () => Capitalize,\n Codec: () => Codec,\n Conditional: () => Conditional,\n Constructor: () => Constructor,\n ConstructorParameters: () => ConstructorParameters,\n Cyclic: () => Cyclic,\n Decode: () => Decode2,\n DecodeBuilder: () => DecodeBuilder,\n Dependent: () => Dependent,\n Encode: () => Encode2,\n EncodeBuilder: () => EncodeBuilder,\n Enum: () => Enum,\n Evaluate: () => Evaluate2,\n Exclude: () => Exclude,\n Extends: () => Extends,\n ExtendsResult: () => result_exports,\n Extract: () => Extract,\n Function: () => _Function_,\n Generic: () => Generic,\n Identifier: () => Identifier,\n Immutable: () => Immutable,\n Index: () => Index,\n Infer: () => Infer,\n InstanceType: () => InstanceType,\n Instantiate: () => Instantiate,\n Integer: () => Integer,\n Interface: () => Interface,\n Intersect: () => Intersect,\n IsAny: () => IsAny,\n IsArray: () => IsArray3,\n IsBigInt: () => IsBigInt3,\n IsBoolean: () => IsBoolean4,\n IsCall: () => IsCall,\n IsCodec: () => IsCodec,\n IsConstructor: () => IsConstructor3,\n IsCyclic: () => IsCyclic,\n IsDependent: () => IsDependent,\n IsEnum: () => IsEnum2,\n IsEnumValue: () => IsEnumValue,\n IsFunction: () => IsFunction3,\n IsGeneric: () => IsGeneric,\n IsIdentifier: () => IsIdentifier2,\n IsImmutable: () => IsImmutable,\n IsInfer: () => IsInfer,\n IsInteger: () => IsInteger3,\n IsIntersect: () => IsIntersect,\n IsKind: () => IsKind,\n IsLiteral: () => IsLiteral,\n IsNever: () => IsNever,\n IsNull: () => IsNull3,\n IsNumber: () => IsNumber4,\n IsObject: () => IsObject3,\n IsOptional: () => IsOptional,\n IsParameter: () => IsParameter,\n IsReadonly: () => IsReadonly,\n IsRecord: () => IsRecord,\n IsRef: () => IsRef2,\n IsRefine: () => IsRefine2,\n IsRest: () => IsRest,\n IsSchema: () => IsSchema2,\n IsString: () => IsString4,\n IsSymbol: () => IsSymbol3,\n IsTemplateLiteral: () => IsTemplateLiteral,\n IsThis: () => IsThis,\n IsTuple: () => IsTuple,\n IsUndefined: () => IsUndefined3,\n IsUnion: () => IsUnion,\n IsUnknown: () => IsUnknown,\n IsUnsafe: () => IsUnsafe,\n IsVoid: () => IsVoid,\n KeyOf: () => KeyOf2,\n Literal: () => Literal,\n Lowercase: () => Lowercase,\n Mapped: () => Mapped,\n Module: () => Module2,\n Never: () => Never,\n NonNullable: () => NonNullable,\n Null: () => Null,\n Number: () => Number2,\n Object: () => _Object_,\n Omit: () => Omit,\n Optional: () => Optional,\n Parameter: () => Parameter,\n Parameters: () => Parameters,\n Partial: () => Partial,\n Pick: () => Pick,\n Readonly: () => Readonly,\n ReadonlyObject: () => ReadonlyObject,\n ReadonlyType: () => ReadonlyType,\n Record: () => Record,\n RecordKey: () => RecordKey,\n RecordPattern: () => RecordPattern,\n RecordValue: () => RecordValue,\n Ref: () => Ref2,\n Refine: () => Refine,\n Required: () => Required,\n Rest: () => Rest,\n ReturnType: () => ReturnType,\n Script: () => Script2,\n String: () => String2,\n Symbol: () => Symbol2,\n TemplateLiteral: () => TemplateLiteral2,\n This: () => This,\n Tuple: () => Tuple,\n Uncapitalize: () => Uncapitalize,\n Undefined: () => Undefined,\n Union: () => Union,\n Unknown: () => Unknown,\n Unsafe: () => Unsafe,\n Uppercase: () => Uppercase,\n Void: () => Void,\n With: () => With2\n });\n\n // node_modules/@earendil-works/pi-ai/dist/utils/event-stream.js\n var FifoQueue = class {\n incoming = [];\n outgoing = [];\n get length() {\n return this.incoming.length + this.outgoing.length;\n }\n enqueue(value) {\n this.incoming.push(value);\n }\n dequeue() {\n if (this.outgoing.length === 0) {\n while (this.incoming.length > 0) {\n this.outgoing.push(this.incoming.pop());\n }\n }\n return this.outgoing.pop();\n }\n };\n var EventStream = class {\n queue = new FifoQueue();\n waiting = new FifoQueue();\n done = false;\n finalResultPromise;\n resolveFinalResult;\n isComplete;\n extractResult;\n constructor(isComplete, extractResult) {\n this.isComplete = isComplete;\n this.extractResult = extractResult;\n this.finalResultPromise = new Promise((resolve2) => {\n this.resolveFinalResult = resolve2;\n });\n }\n push(event) {\n if (this.done)\n return;\n if (this.isComplete(event)) {\n this.done = true;\n this.resolveFinalResult(this.extractResult(event));\n }\n const waiter = this.waiting.dequeue();\n if (waiter) {\n waiter({ value: event, done: false });\n } else {\n this.queue.enqueue(event);\n }\n }\n end(result) {\n this.done = true;\n if (result !== void 0) {\n this.resolveFinalResult(result);\n }\n while (this.waiting.length > 0) {\n const waiter = this.waiting.dequeue();\n waiter({ value: void 0, done: true });\n }\n }\n async *[Symbol.asyncIterator]() {\n while (true) {\n if (this.queue.length > 0) {\n yield this.queue.dequeue();\n } else if (this.done) {\n return;\n } else {\n const result = await new Promise((resolve2) => this.waiting.enqueue(resolve2));\n if (result.done)\n return;\n yield result.value;\n }\n }\n }\n result() {\n return this.finalResultPromise;\n }\n };\n var AssistantMessageEventStream = class extends EventStream {\n #startedAt = Date.now();\n #startedAtMonotonic = performance.now();\n constructor() {\n super((event) => event.type === \"done\" || event.type === \"error\", (event) => {\n if (event.type === \"done\") {\n return event.message;\n } else if (event.type === \"error\") {\n return event.error;\n }\n throw new Error(\"Unexpected event type for final result\");\n });\n }\n push(event) {\n if (event.type === \"done\")\n this.#time(event.message);\n else if (event.type === \"error\")\n this.#time(event.error);\n super.push(event);\n }\n end(result) {\n if (result !== void 0)\n this.#time(result);\n super.end(result);\n }\n #time(message) {\n if (this.done || message.durationMs !== void 0 || message.timestamp < this.#startedAt)\n return;\n message.durationMs = Math.max(0, Math.round(performance.now() - this.#startedAtMonotonic));\n }\n };\n function createAssistantMessageEventStream() {\n return new AssistantMessageEventStream();\n }\n\n // node_modules/@earendil-works/pi-ai/dist/api/lazy.js\n function createSetupErrorMessage(model, error, timestamp) {\n return {\n role: \"assistant\",\n content: [],\n api: model.api,\n provider: model.provider,\n model: model.id,\n usage: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }\n },\n stopReason: \"error\",\n errorMessage: error instanceof Error ? error.message : String(error),\n timestamp\n };\n }\n function hasResult(source) {\n return typeof source.result === \"function\";\n }\n async function forwardStream(target, source) {\n for await (const event of source) {\n target.push(event);\n }\n target.end(hasResult(source) ? await source.result() : void 0);\n }\n function lazyStream(model, setup) {\n const startedAt = Date.now();\n const outer = new AssistantMessageEventStream();\n setup().then((inner) => forwardStream(outer, inner)).catch((error) => {\n const message = createSetupErrorMessage(model, error, startedAt);\n outer.push({ type: \"error\", reason: \"error\", error: message });\n outer.end(message);\n });\n return outer;\n }\n\n // node_modules/@earendil-works/pi-ai/dist/auth/context.js\n var __rewriteRelativeImportExtension = function(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : d + ext + \".\" + cm.toLowerCase() + \"js\";\n });\n }\n return path;\n };\n var importNodeModule = (specifier) => import(__rewriteRelativeImportExtension(specifier));\n function getProcessEnv() {\n const proc = globalThis.process;\n return proc?.env;\n }\n function defaultProviderAuthContext() {\n return {\n async env(name) {\n const value = getProcessEnv()?.[name];\n return typeof value === \"string\" && value.trim().length > 0 ? value : void 0;\n },\n async fileExists(path) {\n try {\n const fs = await importNodeModule(\"node:fs/promises\");\n let resolved = path;\n if (resolved.startsWith(\"~\")) {\n const os = await importNodeModule(\"node:os\");\n resolved = os.homedir() + resolved.slice(1);\n }\n await fs.access(resolved);\n return true;\n } catch {\n return false;\n }\n }\n };\n }\n\n // node_modules/@earendil-works/pi-ai/dist/utils/abort.js\n function abortReason(signal) {\n if (signal.reason !== void 0)\n return signal.reason;\n const error = new Error(\"The operation was aborted\");\n error.name = \"AbortError\";\n return error;\n }\n function operationSignal(signal) {\n return signal ?? new AbortController().signal;\n }\n function raceWithAbortSignal(operation, signal) {\n if (signal.aborted) {\n void operation.catch(() => {\n });\n return Promise.reject(abortReason(signal));\n }\n return new Promise((resolve2, reject) => {\n let settled = false;\n const cleanup = () => signal.removeEventListener(\"abort\", onAbort);\n const onAbort = () => {\n if (settled)\n return;\n settled = true;\n cleanup();\n reject(abortReason(signal));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n void operation.then((value) => {\n if (settled)\n return;\n settled = true;\n cleanup();\n resolve2(value);\n }, (error) => {\n if (settled)\n return;\n settled = true;\n cleanup();\n reject(error);\n });\n if (signal.aborted)\n onAbort();\n });\n }\n\n // node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js\n var InMemoryCredentialStore = class {\n credentials = /* @__PURE__ */ new Map();\n chains = /* @__PURE__ */ new Map();\n /** Serialize tasks per provider id without releasing the chain before active work settles. */\n enqueue(providerId, task, options) {\n const signal = operationSignal(options?.signal);\n const previous = this.chains.get(providerId) ?? Promise.resolve();\n const queued2 = (async () => {\n await previous.catch(() => {\n });\n signal.throwIfAborted();\n return task();\n })();\n const tail = queued2.catch(() => {\n });\n this.chains.set(providerId, tail);\n void tail.then(() => {\n if (this.chains.get(providerId) === tail)\n this.chains.delete(providerId);\n });\n return raceWithAbortSignal(queued2, signal);\n }\n async read(providerId, options) {\n options?.signal?.throwIfAborted();\n return this.credentials.get(providerId);\n }\n async list(options) {\n options?.signal?.throwIfAborted();\n return [...this.credentials].map(([providerId, credential]) => ({ providerId, type: credential.type }));\n }\n modify(providerId, fn, options) {\n return this.enqueue(providerId, async () => {\n const current = this.credentials.get(providerId);\n const next = await fn(current);\n options?.signal?.throwIfAborted();\n if (next !== void 0)\n this.credentials.set(providerId, next);\n return next ?? current;\n }, options);\n }\n delete(providerId, options) {\n return this.enqueue(providerId, async () => {\n this.credentials.delete(providerId);\n }, options);\n }\n };\n\n // node_modules/@earendil-works/pi-ai/dist/utils/diagnostics.js\n function formatThrownValue(value) {\n if (value instanceof Error)\n return value.message || value.name;\n if (typeof value === \"string\")\n return value;\n return String(value);\n }\n\n // node_modules/@earendil-works/pi-ai/dist/utils/models-error.js\n var ModelsError = class extends Error {\n code;\n constructor(code, message, options) {\n super(withCauseDetail(message, options?.cause), options);\n this.name = \"ModelsError\";\n this.code = code;\n }\n };\n function withCauseDetail(message, cause) {\n if (cause === void 0 || cause === null)\n return message;\n const detail = formatThrownValue(cause).trim();\n if (!detail || message.includes(detail))\n return message;\n return `${message}: ${detail}`;\n }\n\n // node_modules/@earendil-works/pi-ai/dist/auth/resolve.js\n function resolveProviderAuth(provider, credentials, authContext, overrides) {\n const signal = operationSignal(overrides?.signal);\n return raceWithAbortSignal(resolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal), signal);\n }\n async function resolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal) {\n signal.throwIfAborted();\n const requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;\n if (overrides?.apiKey !== void 0 && provider.auth.apiKey) {\n return resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, {\n type: \"api_key\",\n key: overrides.apiKey,\n env: overrides.env\n }, signal);\n }\n const stored = await readCredential(credentials, provider.id, signal);\n if (stored) {\n if (stored.type === \"oauth\" && provider.auth.oauth) {\n return resolveStoredOAuth(credentials, provider.id, provider.auth.oauth, stored, signal, overrides?.minOAuthValidityMs);\n }\n if (stored.type === \"api_key\" && provider.auth.apiKey) {\n const credential = overrides?.env ? { ...stored, env: { ...stored.env, ...overrides.env } } : stored;\n return resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, credential, signal);\n }\n return void 0;\n }\n return provider.auth.apiKey ? resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, void 0, signal) : void 0;\n }\n function overlayEnvAuthContext(base, env) {\n return {\n env: async (name) => env[name] || await base.env(name),\n fileExists: (path) => base.fileExists(path)\n };\n }\n var DEFAULT_OAUTH_MINIMUM_VALIDITY_MS = 5 * 60 * 1e3;\n var DEFAULT_OAUTH_REFRESH_TIMEOUT_MS = 15e3;\n async function refreshStoredOAuthCredential(credentials, providerId, oauth, needsRefresh, signal) {\n let post;\n const lockWait = new AbortController();\n const cancelLockWait = () => lockWait.abort(signal.reason);\n signal.addEventListener(\"abort\", cancelLockWait, { once: true });\n if (signal.aborted)\n cancelLockWait();\n try {\n post = await credentials.modify(providerId, async (current) => {\n signal.removeEventListener(\"abort\", cancelLockWait);\n signal.throwIfAborted();\n if (current?.type !== \"oauth\")\n return void 0;\n if (!needsRefresh(current))\n return void 0;\n try {\n return await oauth.refresh(current, AbortSignal.timeout(DEFAULT_OAUTH_REFRESH_TIMEOUT_MS));\n } catch (error) {\n throw new ModelsError(\"oauth\", `OAuth refresh failed for ${providerId}`, { cause: error });\n }\n }, { signal: lockWait.signal });\n } catch (error) {\n if (error instanceof ModelsError)\n throw error;\n signal.throwIfAborted();\n throw new ModelsError(\"auth\", `Credential store modify failed for ${providerId}`, { cause: error });\n } finally {\n signal.removeEventListener(\"abort\", cancelLockWait);\n }\n return post?.type === \"oauth\" ? post : void 0;\n }\n async function resolveStoredOAuth(credentials, providerId, oauth, stored, signal, minOAuthValidityMs) {\n const minimumValidityMs = Math.max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS, minOAuthValidityMs ?? 0);\n const expiresSoon = (credential2) => Date.now() + minimumValidityMs >= credential2.expires;\n let credential = stored;\n if (expiresSoon(credential)) {\n const post = await refreshStoredOAuthCredential(credentials, providerId, oauth, expiresSoon, signal);\n if (!post)\n return void 0;\n credential = post;\n if (minOAuthValidityMs !== void 0 && expiresSoon(credential)) {\n throw new ModelsError(\"oauth\", `OAuth refresh returned a token that expires too soon for ${providerId}`);\n }\n }\n try {\n return { auth: await oauth.toAuth(credential), source: \"OAuth\" };\n } catch (error) {\n throw new ModelsError(\"oauth\", `OAuth auth derivation failed for ${providerId}`, { cause: error });\n }\n }\n async function resolveApiKey(authContext, apiKey, providerId, credential, signal) {\n try {\n return await apiKey.resolve({ ctx: authContext, credential, signal });\n } catch (error) {\n throw new ModelsError(\"auth\", `API key auth failed for provider ${providerId}`, { cause: error });\n }\n }\n async function readCredential(credentials, providerId, signal) {\n try {\n return await credentials.read(providerId, { signal });\n } catch (error) {\n throw new ModelsError(\"auth\", `Credential store read failed for ${providerId}`, { cause: error });\n }\n }\n\n // node_modules/@earendil-works/pi-ai/dist/models-store.js\n var InMemoryModelsStore = class {\n entries = /* @__PURE__ */ new Map();\n async read(providerId, options) {\n options?.signal?.throwIfAborted();\n const entry = this.entries.get(providerId);\n return entry ? structuredClone(entry) : void 0;\n }\n async write(providerId, entry, options) {\n options?.signal?.throwIfAborted();\n this.entries.set(providerId, structuredClone(entry));\n }\n async delete(providerId, options) {\n options?.signal?.throwIfAborted();\n this.entries.delete(providerId);\n }\n };\n\n // node_modules/@earendil-works/pi-ai/dist/utils/model-operations.js\n function getModelType(model) {\n return model.type ?? \"chat\";\n }\n function isModelType(model, type) {\n return getModelType(model) === type;\n }\n function assertChatModel(model) {\n if (!isModelType(model, \"chat\")) {\n throw new ModelsError(\"provider\", `Model ${model.provider}/${model.id} is not a chat model`);\n }\n }\n function assertImageModel(model) {\n if (!isModelType(model, \"image\")) {\n throw new ModelsError(\"provider\", `Model ${model.provider}/${model.id} is not an image model`);\n }\n }\n function assertClassifierModel(model) {\n if (!isModelType(model, \"classifier\")) {\n throw new ModelsError(\"provider\", `Model ${model.provider}/${model.id} is not a classifier model`);\n }\n }\n function assertClassifierInputSupported(model, context2) {\n if (context2.images?.length && !model.input.includes(\"image\")) {\n throw new ModelsError(\"provider\", `Model ${model.provider}/${model.id} does not accept image input`);\n }\n }\n function imageErrorResult(model, error, aborted = false) {\n return {\n api: model.api,\n provider: model.provider,\n model: model.id,\n output: [],\n stopReason: aborted ? \"aborted\" : \"error\",\n errorMessage: error instanceof Error ? error.message : String(error),\n timestamp: Date.now()\n };\n }\n function classifierErrorResult(model, error, aborted = false) {\n return {\n api: model.api,\n provider: model.provider,\n model: model.id,\n answers: {},\n stopReason: aborted ? \"aborted\" : \"error\",\n errorMessage: error instanceof Error ? error.message : String(error),\n timestamp: Date.now()\n };\n }\n\n // node_modules/@earendil-works/pi-ai/dist/models.js\n var KNOWN_MODEL_TYPES = { chat: true, image: true, classifier: true };\n function hasKnownModelType(model) {\n return Object.hasOwn(KNOWN_MODEL_TYPES, getModelType(model));\n }\n function withKnownModelTypes(entry) {\n return { ...entry, models: entry.models.filter(hasKnownModelType) };\n }\n function mergeHeaders(base, override) {\n if (!base && !override)\n return void 0;\n const merged = { ...base };\n for (const [name, value] of Object.entries(override ?? {})) {\n const lowerName = name.toLowerCase();\n for (const existingName of Object.keys(merged)) {\n if (existingName.toLowerCase() === lowerName)\n delete merged[existingName];\n }\n merged[name] = value;\n }\n return merged;\n }\n var ModelsImpl = class {\n providers = /* @__PURE__ */ new Map();\n credentials;\n modelsStore;\n authContext;\n refreshGenerations = /* @__PURE__ */ new Map();\n refreshControllers = /* @__PURE__ */ new Map();\n publicationChains = /* @__PURE__ */ new Map();\n constructor(options) {\n this.credentials = options?.credentials ?? new InMemoryCredentialStore();\n this.modelsStore = options?.modelsStore ?? new InMemoryModelsStore();\n this.authContext = options?.authContext ?? defaultProviderAuthContext();\n }\n setProvider(provider) {\n this.supersedeProviderRefresh(provider.id);\n this.providers.set(provider.id, provider);\n }\n deleteProvider(id) {\n this.supersedeProviderRefresh(id);\n this.providers.delete(id);\n }\n clearProviders() {\n for (const id of /* @__PURE__ */ new Set([...this.providers.keys(), ...this.refreshControllers.keys()])) {\n this.supersedeProviderRefresh(id);\n }\n this.providers.clear();\n }\n getProviders() {\n return Array.from(this.providers.values());\n }\n getProvider(id) {\n return this.providers.get(id);\n }\n getModels(provider) {\n if (provider !== void 0) {\n const entry = this.providers.get(provider);\n if (!entry)\n return [];\n try {\n return entry.getModels();\n } catch {\n return [];\n }\n }\n const models = [];\n for (const entry of this.providers.values()) {\n try {\n models.push(...entry.getModels());\n } catch {\n }\n }\n return models;\n }\n getAllModels(provider) {\n if (provider !== void 0) {\n const entry = this.providers.get(provider);\n if (!entry)\n return [];\n try {\n return entry.getAllModels?.() ?? entry.getModels();\n } catch {\n return [];\n }\n }\n const models = [];\n for (const entry of this.providers.values()) {\n try {\n models.push(...entry.getAllModels?.() ?? entry.getModels());\n } catch {\n }\n }\n return models;\n }\n getModelsOfType(type, provider) {\n return this.getAllModels(provider).filter((model) => isModelType(model, type));\n }\n getModel(provider, id) {\n return this.getModels(provider).find((model) => model.id === id);\n }\n getModelOfType(type, provider, id) {\n return this.getModelsOfType(type, provider).find((model) => model.id === id);\n }\n supersedeProviderRefresh(providerId) {\n const generation = (this.refreshGenerations.get(providerId) ?? 0) + 1;\n this.refreshGenerations.set(providerId, generation);\n const previous = this.refreshControllers.get(providerId);\n if (previous) {\n this.refreshControllers.delete(providerId);\n previous.abort();\n }\n return generation;\n }\n beginProviderRefresh(providerId) {\n const generation = this.supersedeProviderRefresh(providerId);\n const controller = new AbortController();\n this.refreshControllers.set(providerId, controller);\n return { generation, controller };\n }\n publishProviderModels(providerId, generation, signal, publication) {\n const previous = this.publicationChains.get(providerId) ?? Promise.resolve();\n const queued2 = (async () => {\n await previous.catch(() => {\n });\n if (signal.aborted || this.refreshGenerations.get(providerId) !== generation)\n return false;\n if (publication.persist === null) {\n await this.modelsStore.delete(providerId, { signal });\n } else if (publication.persist !== void 0) {\n await this.modelsStore.write(providerId, structuredClone(publication.persist), { signal });\n }\n if (signal.aborted || this.refreshGenerations.get(providerId) !== generation)\n return false;\n publication.update?.();\n return true;\n })();\n const tail = queued2.catch(() => {\n });\n this.publicationChains.set(providerId, tail);\n void tail.then(() => {\n if (this.publicationChains.get(providerId) === tail)\n this.publicationChains.delete(providerId);\n });\n return raceWithAbortSignal(queued2, signal);\n }\n async runProviderRefreshPhase(provider, credential, allowNetwork, force, generation, signal) {\n const stored = await this.modelsStore.read(provider.id, { signal });\n await provider.refreshModels({\n credential,\n stored: stored ? withKnownModelTypes(structuredClone(stored)) : void 0,\n publish: (publication) => this.publishProviderModels(provider.id, generation, signal, publication),\n allowNetwork,\n force: allowNetwork ? force : void 0,\n signal\n });\n }\n async refresh(options = {}) {\n const allowNetwork = options.allowNetwork ?? true;\n const callerSignal = operationSignal(options.signal);\n const errors = /* @__PURE__ */ new Map();\n if (callerSignal.aborted)\n return { aborted: true, errors };\n const selected = options.providers ? new Set(options.providers) : void 0;\n const refreshable = Array.from(this.providers.values()).filter((provider) => provider.refreshModels !== void 0 && (!selected || selected.has(provider.id)));\n const refresh = Promise.all(refreshable.map(async (provider) => {\n const { generation, controller } = this.beginProviderRefresh(provider.id);\n const signal = AbortSignal.any([callerSignal, controller.signal]);\n const operation = (async () => {\n let storedCredential;\n let credentialError;\n try {\n storedCredential = await this.readCredential(provider.id, signal);\n } catch (error) {\n credentialError = error;\n }\n await this.runProviderRefreshPhase(provider, storedCredential, false, void 0, generation, signal);\n if (credentialError !== void 0)\n throw credentialError;\n if (!allowNetwork || signal.aborted)\n return;\n const credential = await this.resolveRefreshCredential(provider, storedCredential, signal);\n if (!credential)\n return;\n await this.runProviderRefreshPhase(provider, credential, true, options.force, generation, signal);\n })();\n try {\n await raceWithAbortSignal(operation, signal);\n } catch (error) {\n if (!signal.aborted) {\n errors.set(provider.id, error instanceof Error ? error : new ModelsError(\"model_source\", `Model refresh failed for ${provider.id}`, { cause: error }));\n }\n } finally {\n if (this.refreshControllers.get(provider.id) === controller) {\n this.refreshControllers.delete(provider.id);\n }\n }\n }));\n try {\n await raceWithAbortSignal(refresh, callerSignal);\n } catch (error) {\n if (!callerSignal.aborted)\n throw error;\n }\n return { aborted: callerSignal.aborted, errors: new Map(errors) };\n }\n async resolveRefreshCredential(provider, stored, signal) {\n if (stored?.type === \"oauth\") {\n const oauth = provider.auth.oauth;\n if (!oauth)\n return void 0;\n if (Date.now() < stored.expires)\n return stored;\n if (signal.aborted)\n return void 0;\n return refreshStoredOAuthCredential(this.credentials, provider.id, oauth, (current) => Date.now() >= current.expires, signal);\n }\n const apiKey = provider.auth.apiKey;\n if (!apiKey)\n return void 0;\n const credential = stored?.type === \"api_key\" ? stored : void 0;\n const result = await apiKey.resolve({ ctx: this.authContext, credential, signal });\n if (!result)\n return void 0;\n return { type: \"api_key\", key: result.auth.apiKey, env: result.env };\n }\n async readCredential(providerId, signal) {\n try {\n return await this.credentials.read(providerId, { signal });\n } catch (error) {\n throw new ModelsError(\"auth\", `Credential store read failed for ${providerId}`, { cause: error });\n }\n }\n async checkProviderAuth(provider, credential, signal) {\n if (credential?.type === \"oauth\") {\n return provider.auth.oauth ? { source: \"OAuth\", type: \"oauth\" } : void 0;\n }\n const apiKey = provider.auth.apiKey;\n if (!apiKey)\n return void 0;\n if (apiKey.check) {\n try {\n return await apiKey.check({\n ctx: this.authContext,\n credential: credential?.type === \"api_key\" ? credential : void 0,\n signal\n });\n } catch (error) {\n throw new ModelsError(\"auth\", `API key auth check failed for provider ${provider.id}`, { cause: error });\n }\n }\n const resolution = await resolveProviderAuth(provider, this.credentials, this.authContext, { signal });\n return resolution ? { source: resolution.source, type: \"api_key\" } : void 0;\n }\n checkAuth(providerId, options) {\n const signal = operationSignal(options?.signal);\n const check = (async () => {\n signal.throwIfAborted();\n const provider = this.providers.get(providerId);\n if (!provider)\n return void 0;\n return this.checkProviderAuth(provider, await this.readCredential(providerId, signal), signal);\n })();\n return raceWithAbortSignal(check, signal);\n }\n async getAuthenticatedProviders(providerId, signal) {\n signal.throwIfAborted();\n const providers = providerId ? [this.providers.get(providerId)].filter((entry) => entry !== void 0) : this.getProviders();\n const checks = await Promise.all(providers.map(async (provider) => {\n const credential = await this.readCredential(provider.id, signal);\n return { provider, credential, auth: await this.checkProviderAuth(provider, credential, signal) };\n }));\n return checks.filter((entry) => entry.auth !== void 0);\n }\n getAvailable(providerId, options) {\n const signal = operationSignal(options?.signal);\n const available = (async () => {\n const providers = await this.getAuthenticatedProviders(providerId, signal);\n return providers.flatMap(({ provider, credential }) => {\n const models = provider.getModels();\n return provider.filterModels?.(models, credential) ?? models;\n });\n })();\n return raceWithAbortSignal(available, signal);\n }\n async getAvailableOfType(type, providerId, options) {\n return (await this.getAllAvailable(providerId, options)).filter((model) => isModelType(model, type));\n }\n getAllAvailable(providerId, options) {\n const signal = operationSignal(options?.signal);\n const available = (async () => {\n const providers = await this.getAuthenticatedProviders(providerId, signal);\n return providers.flatMap(({ provider, credential }) => {\n const models = provider.getAllModels?.() ?? provider.getModels();\n if (provider.filterAllModels)\n return provider.filterAllModels(models, credential);\n if (!provider.filterModels)\n return models;\n const availableChatIds = new Set(provider.filterModels(provider.getModels(), credential).map((model) => model.id));\n return models.filter((model) => !isModelType(model, \"chat\") || availableChatIds.has(model.id));\n });\n })();\n return raceWithAbortSignal(available, signal);\n }\n async getAuth(providerOrModel, overrides) {\n const signal = operationSignal(overrides?.signal);\n const providerId = typeof providerOrModel === \"string\" ? providerOrModel : providerOrModel.provider;\n const provider = this.providers.get(providerId);\n if (!provider)\n return void 0;\n const result = await resolveProviderAuth(provider, this.credentials, this.authContext, { ...overrides, signal });\n if (!result || typeof providerOrModel === \"string\" || !providerOrModel.headers)\n return result;\n return {\n ...result,\n auth: {\n ...result.auth,\n headers: mergeHeaders(result.auth.headers, providerOrModel.headers)\n }\n };\n }\n async login(providerId, type, interaction, options) {\n const signal = operationSignal(interaction.signal);\n signal.throwIfAborted();\n const provider = this.providers.get(providerId);\n if (!provider)\n throw new ModelsError(\"provider\", `Unknown provider: ${providerId}`);\n const method = type === \"oauth\" ? provider.auth.oauth : provider.auth.apiKey;\n if (!method?.login) {\n throw new ModelsError(\"auth\", `${provider.name} does not support ${type} login`);\n }\n const loginOperation = method.login({ ...interaction, signal }, options);\n const credential = await raceWithAbortSignal(loginOperation, signal);\n let mutationStarted = false;\n let markMutationStarted;\n const started = new Promise((resolve2) => {\n markMutationStarted = resolve2;\n });\n const mutation = this.credentials.modify(providerId, async () => {\n mutationStarted = true;\n markMutationStarted?.();\n return credential;\n }, { signal });\n void mutation.catch(() => {\n });\n try {\n await new Promise((resolve2, reject) => {\n const onAbort = () => {\n if (!mutationStarted)\n reject(signal.reason);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n void Promise.race([started, mutation]).then(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve2();\n }, (error) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n });\n if (signal.aborted)\n onAbort();\n });\n await mutation;\n } catch (error) {\n signal.throwIfAborted();\n throw new ModelsError(\"auth\", `Credential store modify failed for ${providerId}`, { cause: error });\n }\n return credential;\n }\n async logout(providerId, options) {\n const signal = operationSignal(options?.signal);\n signal.throwIfAborted();\n try {\n await this.credentials.delete(providerId, { signal });\n } catch (error) {\n signal.throwIfAborted();\n throw new ModelsError(\"auth\", `Credential store delete failed for ${providerId}`, { cause: error });\n }\n }\n requireProvider(model) {\n const provider = this.providers.get(model.provider);\n if (!provider) {\n throw new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n }\n return provider;\n }\n requireChatProvider(model) {\n assertChatModel(model);\n return this.requireProvider(model);\n }\n async applyAuth(model, options) {\n this.requireProvider(model);\n const resolution = await this.getAuth(model, {\n apiKey: options?.apiKey,\n env: options?.env,\n signal: options?.signal\n });\n if (!resolution) {\n throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n }\n const auth = resolution.auth;\n const apiKey = options?.apiKey ?? auth.apiKey;\n let headers = mergeHeaders(auth.headers, options?.headers);\n if (options?.transformHeaders)\n headers = await options.transformHeaders(headers ?? {});\n const env = resolution.env || options?.env ? { ...resolution.env ?? {}, ...options?.env ?? {} } : void 0;\n const requestModel = auth.baseUrl ? { ...model, baseUrl: auth.baseUrl } : model;\n const { transformHeaders: _transformHeaders, ...providerOptions } = options ?? {};\n const requestOptions = { ...providerOptions, apiKey, headers, env };\n return { requestModel, requestOptions };\n }\n stream(model, context2, options) {\n const transcript = normalizeContext(context2);\n return lazyStream(model, async () => {\n const provider = this.requireChatProvider(model);\n const { requestModel, requestOptions } = await this.applyAuth(model, options);\n return provider.stream(requestModel, transcript, requestOptions);\n });\n }\n async complete(model, context2, options) {\n return this.stream(model, context2, options).result();\n }\n streamSimple(model, context2, options) {\n const transcript = normalizeContext(context2);\n return lazyStream(model, async () => {\n const provider = this.requireChatProvider(model);\n const { requestModel, requestOptions } = await this.applyAuth(model, options);\n return provider.streamSimple(requestModel, transcript, requestOptions);\n });\n }\n async completeSimple(model, context2, options) {\n return this.streamSimple(model, context2, options).result();\n }\n streamDeferred(model, handle, options) {\n return lazyStream(model, async () => {\n const provider = this.requireChatProvider(model);\n if (!provider.fetchDeferred) {\n throw new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n }\n const { requestModel, requestOptions } = await this.applyAuth(model, options);\n return provider.fetchDeferred(requestModel, handle, requestOptions);\n });\n }\n async fetchDeferred(model, handle, options) {\n return this.streamDeferred(model, handle, options).result();\n }\n async cancelDeferred(model, handle, options) {\n const provider = this.requireChatProvider(model);\n if (!provider.cancelDeferred) {\n throw new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n }\n const { requestModel, requestOptions } = await this.applyAuth(model, options);\n await provider.cancelDeferred(requestModel, handle, requestOptions);\n }\n async generateImages(model, context2, options) {\n try {\n assertImageModel(model);\n const provider = this.requireProvider(model);\n if (!provider.generateImages) {\n throw new ModelsError(\"provider\", `Provider ${model.provider} does not support image generation`);\n }\n const { requestModel, requestOptions } = await this.applyAuth(model, options);\n return await provider.generateImages(requestModel, context2, requestOptions);\n } catch (error) {\n return imageErrorResult(model, error, options?.signal?.aborted);\n }\n }\n async classify(model, context2, options) {\n try {\n assertClassifierModel(model);\n assertClassifierInputSupported(model, context2);\n const provider = this.requireProvider(model);\n if (!provider.classify) {\n throw new ModelsError(\"provider\", `Provider ${model.provider} does not support classification`);\n }\n const { requestModel, requestOptions } = await this.applyAuth(model, options);\n return await provider.classify(requestModel, context2, requestOptions);\n } catch (error) {\n return classifierErrorResult(model, error, options?.signal?.aborted);\n }\n }\n };\n function createModels(options) {\n return new ModelsImpl(options);\n }\n function createProvider(input) {\n const single = input.api && typeof input.api.stream === \"function\" ? input.api : void 0;\n const byApi = single || !input.api ? void 0 : input.api;\n const images = input.images;\n const classifiers = input.classifiers;\n const streams = single ? [single] : Object.values(byApi ?? {}).filter((entry) => entry !== void 0);\n const imageImplementations = Object.values(images ?? {}).filter((entry) => entry !== void 0);\n const classifierImplementations = Object.values(classifiers ?? {}).filter((entry) => entry !== void 0);\n if (streams.length === 0 && imageImplementations.length === 0 && classifierImplementations.length === 0) {\n throw new Error(`Provider ${input.id}: at least one of \"api\", \"images\", or \"classifiers\" is required.`);\n }\n const baselineModels = input.models;\n let dynamicModels = [];\n const fetchModels = input.fetchModels;\n const currentModels = () => {\n const merged = [...baselineModels];\n for (const model of dynamicModels) {\n const index3 = merged.findIndex((entry) => getModelType(entry) === getModelType(model) && entry.id === model.id);\n if (index3 >= 0)\n merged[index3] = model;\n else\n merged.push(model);\n }\n return merged;\n };\n const apiFor = (model) => single ?? byApi?.[model.api];\n const dispatch = (model, run2) => {\n const streams2 = apiFor(model);\n if (!streams2) {\n return lazyStream(model, async () => {\n throw new ModelsError(\"stream\", `Provider ${input.id} has no API implementation for \"${model.api}\"`);\n });\n }\n return run2(streams2);\n };\n const provider = {\n id: input.id,\n name: input.name ?? input.id,\n baseUrl: input.baseUrl,\n headers: input.headers,\n auth: input.auth,\n getModels: () => currentModels().filter((model) => isModelType(model, \"chat\")),\n getAllModels: currentModels,\n refreshModels: fetchModels ? async (context2) => {\n if (context2.stored) {\n const restored = context2.stored.models.filter((model) => model.provider === input.id).map((model) => model);\n if (!await context2.publish({\n update: () => {\n dynamicModels = restored;\n }\n })) {\n return;\n }\n }\n if (!context2.allowNetwork || context2.signal.aborted)\n return;\n const fetched = await fetchModels(context2);\n if (context2.signal.aborted)\n return;\n const refreshed = fetched.filter(hasKnownModelType);\n await context2.publish({\n persist: { models: refreshed, checkedAt: Date.now() },\n update: () => {\n dynamicModels = refreshed;\n }\n });\n } : void 0,\n filterModels: input.filterModels,\n filterAllModels: input.filterAllModels,\n stream: (model, context2, options) => dispatch(model, (streams2) => streams2.stream(model, context2, options)),\n streamSimple: (model, context2, options) => dispatch(model, (streams2) => streams2.streamSimple(model, context2, options))\n };\n if (streams.some((entry) => entry.fetchDeferred !== void 0)) {\n provider.fetchDeferred = (model, handle, options) => lazyStream(model, async () => {\n const implementation = apiFor(model);\n if (!implementation?.fetchDeferred) {\n throw new ModelsError(\"provider\", `Provider ${input.id} does not support deferred responses for \"${model.api}\"`);\n }\n return implementation.fetchDeferred(model, handle, options);\n });\n }\n if (streams.some((entry) => entry.cancelDeferred !== void 0)) {\n provider.cancelDeferred = async (model, handle, options) => {\n const implementation = apiFor(model);\n if (!implementation?.cancelDeferred) {\n throw new ModelsError(\"provider\", `Provider ${input.id} cannot cancel deferred responses for \"${model.api}\"`);\n }\n await implementation.cancelDeferred(model, handle, options);\n };\n }\n if (images && imageImplementations.length > 0) {\n provider.generateImages = async (model, context2, options) => {\n const implementation = images[model.api];\n if (!implementation) {\n return imageErrorResult(model, new ModelsError(\"provider\", `Provider ${input.id} has no image generation implementation for \"${model.api}\"`));\n }\n return implementation.generateImages(model, context2, options);\n };\n }\n if (classifiers && classifierImplementations.length > 0) {\n provider.classify = async (model, context2, options) => {\n const implementation = classifiers[model.api];\n if (!implementation) {\n return classifierErrorResult(model, new ModelsError(\"provider\", `Provider ${input.id} has no classifier implementation for \"${model.api}\"`));\n }\n return implementation.classify(model, context2, options);\n };\n }\n return provider;\n }\n\n // src/guest/journal.ts\n var JournalStorage = class _JournalStorage extends MemoryStorage {\n static async open() {\n const storage = new _JournalStorage();\n const commits = JSON.parse(await __host(\"load\", \"{}\"));\n let expected = 1;\n for (const commit of commits) {\n if (commit.seq !== expected++) throw new Error(\"Journal sequence is corrupt\");\n storage.prepareCommit(commit.writes, commit.seq).apply();\n }\n return storage;\n }\n async commit(writes) {\n const prepared = this.prepareCommit(writes);\n await __host(\"append\", JSON.stringify({ seq: prepared.seq, writes: prepared.writes }));\n return prepared.apply();\n }\n async close() {\n await super.close(BACKGROUND_CONTEXT);\n }\n };\n\n // src/guest/bridge.ts\n var nextId = 1;\n async function hostCall(name, value, signal, update) {\n signal?.throwIfAborted();\n const id = nextId++;\n const abort2 = () => __cancel(id);\n const pending = __host(name, JSON.stringify(value), (raw) => update?.(JSON.parse(raw)), id);\n signal?.addEventListener(\"abort\", abort2, { once: true });\n try {\n return JSON.parse(await pending);\n } finally {\n signal?.removeEventListener(\"abort\", abort2);\n }\n }\n\n // src/guest/entry.ts\n var context = BACKGROUND_CONTEXT;\n var harness;\n var root;\n var registry = createRegistry();\n var watches = /* @__PURE__ */ new Map();\n var usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };\n function stream(model, transcript, options) {\n const events = createAssistantMessageEventStream();\n void hostCall(\"model\", { model, context: transcript, options: { ...options, signal: void 0 } }, options?.signal, (event) => events.push(event)).then((message) => {\n if (message.stopReason === \"error\" || message.stopReason === \"aborted\") events.push({ type: \"error\", reason: message.stopReason, error: message });\n else events.push({ type: \"done\", reason: message.stopReason, message });\n events.end(message);\n }, (error) => {\n const message = { role: \"assistant\", api: \"host\", provider: \"host\", model: model.id, content: [], usage, stopReason: options?.signal?.aborted ? \"aborted\" : \"error\", errorMessage: String(error), timestamp: Date.now() };\n events.push({ type: \"error\", reason: message.stopReason, error: message });\n events.end(message);\n });\n return events;\n }\n function install(source) {\n const module = { exports: {} };\n const require2 = (name) => {\n if (name === \"@earendil-works/pi-durable\") return dist_exports;\n if (name === \"@earendil-works/pi-ai\") return { Type: typebox_exports };\n if (name === \"@earendil-works/chord/context\") return context_exports;\n throw new Error(`Guest module not available: ${name}`);\n };\n new Function(\"module\", \"exports\", \"require\", source)(module, module.exports, require2);\n const extension = module.exports.default ?? module.exports;\n registry.install(extension);\n return extension.name;\n }\n async function conversation(args) {\n if (args.conversationId === void 0) return root;\n const found = await harness.conversation(args.conversationId, context);\n if (!found) throw new Error(\"Conversation not found\");\n return found;\n }\n async function watch(id) {\n if (watches.has(id)) return;\n const stream2 = await watchEvents(harness, id, context);\n watches.set(id, stream2);\n const emit = (events) => __emit(JSON.stringify({ type: \"events\", conversationId: id, events }));\n emit([stream2.snapshot]);\n stream2.start(async (events) => {\n emit(events);\n });\n }\n async function open(config) {\n const models = createModels();\n models.setProvider(createProvider({ id: \"host\", auth: { apiKey: { name: \"Host\", resolve: async () => ({ auth: {} }) } }, models: [{ id: config.modelId ?? \"host-model\", name: \"Host model\", provider: \"host\", baseUrl: \"host://model\", api: \"host\", reasoning: true, input: [\"text\", \"image\"], cost: usage.cost, contextWindow: config.contextWindow ?? 32768, maxTokens: 4096 }], api: { stream, streamSimple: stream } }));\n registry.install(defineExtension({ name: \"host-tools\", tools: config.tools.map((tool) => defineTool({ ...tool, execute: async (args, api2, ctx) => {\n const result = await hostCall(\"tool\", { name: tool.name, args, taskId: api2.taskId, conversationId: api2.conversationId, callId: api2.callId }, ctx.abortSignal, (update) => {\n if (update.type === \"output\") api2.output(update.text);\n });\n return typeof result === \"string\" ? { content: [{ type: \"text\", text: result }] } : result;\n } })) }));\n for (const source of config.extensions ?? []) install(source);\n harness = await Harness.open(await JournalStorage.open(), { models, registry, settings: config.settings, onReport: (error) => __emit(JSON.stringify({ type: \"error\", message: String(error) })) }, context);\n root = await harness.root(context, { agent: { model: { provider: \"host\", modelId: config.modelId ?? \"host-model\" }, instructions: config.instructions ?? \"You are a helpful assistant.\" } });\n if (config.events) await watch(root.id);\n if (config.autoResume !== false) harness.resume();\n return { conversationId: root.id };\n }\n var api = {\n open,\n resume: async () => {\n harness.resume();\n return null;\n },\n submit: async (args) => ({ id: (await (await conversation(args)).submit(args.submission, context)).id }),\n wait: async (args) => {\n const submission = await harness.submission(args.id, context);\n if (!submission) throw new Error(\"Submission not found\");\n return submission.wait(context);\n },\n view: async (args) => {\n const state2 = await (await conversation(args)).viewState(context);\n try {\n return state2.value;\n } finally {\n state2.dispose();\n }\n },\n context: async (args) => (await conversation(args)).context(context, args.at === void 0 ? {} : { at: args.at }),\n configure: async (args) => {\n const change = { ...args.change };\n const snapshot = registry.snapshot();\n if (change.extensions) change.extensions = change.extensions.map((name) => {\n const ext = snapshot.extension(name);\n if (!ext) throw new Error(`Unknown extension: ${name}`);\n return ext;\n });\n if (change.tools) change.tools = change.tools.map((name) => {\n const tool = snapshot.tools().find((t) => t.tool.name === name)?.tool;\n if (!tool) throw new Error(`Unknown tool: ${name}`);\n return tool;\n });\n await (await conversation(args)).configure(change, context);\n return null;\n },\n createConversation: async (args) => ({ conversationId: (await harness.createConversation({ ownership: { kind: \"ownerless\" }, agent: args.agent }, context)).id }),\n fork: async (args) => ({ conversationId: (await (await conversation(args)).fork(args.at, { ownership: { kind: \"ownerless\" } }, context)).id }),\n reset: async (args) => {\n await (await conversation(args)).reset(args.handoff, context);\n return null;\n },\n compact: async (args) => ({ taskId: await (await conversation(args)).compact(args.instructions, context) }),\n waitForTask: async (args) => harness.waitForTask(args.id, context),\n inspect: async () => harness.inspect(context),\n taskGraph: async () => {\n const state2 = await harness.taskGraph(context);\n try {\n return state2.value;\n } finally {\n state2.dispose();\n }\n },\n abort: async (args) => {\n await (await conversation(args)).abort(context, { background: args.background });\n return null;\n },\n abortSubmission: async (args) => harness.abortSubmission(args.id, context),\n watch: async (args) => {\n await watch((await conversation(args)).id);\n return null;\n },\n install: async (args) => install(args.source),\n uninstall: async (args) => {\n registry.uninstall({ name: args.name });\n return null;\n },\n evaluate: async (args) => {\n const fn = new Function(\"pi\", \"Type\", \"harness\", \"conversation\", \"registry\", \"context\", \"args\", `return (async () => { ${args.source}\n })()`);\n return fn(dist_exports, typebox_exports, harness, await conversation(args), registry, context, args.args);\n },\n close: async () => {\n for (const stream2 of watches.values()) await stream2.stop();\n watches.clear();\n await harness.close(context);\n return null;\n }\n };\n globalThis.__dispatch = async (method, raw) => {\n if (!Object.hasOwn(api, method)) throw new Error(\"Unknown guest method\");\n return JSON.stringify(await api[method](JSON.parse(raw)) ?? null);\n };\n})();\n";
|
|
3
|
+
export default source;
|