dsh-subagent-library 0.2.0 → 0.2.3

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/lib/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":["name","pick","deepFreeze","hasIntrinsicConstructor","name","isIntrinsicObjectPrototype","hasPlainArrayPrototype","target","SessionPreparation","name","required","registry","parts","describe","union","node","deepFreeze","config","unknown","meta","_a","name","object","isPlainObject","_a","config","initializer","util.jsonStringifyReplacer","issue","error","core.$ZodAsyncError","util.finalizeIssue","core.config","parse","errors.$ZodRealError","parseAsync","errors.$ZodError","safeParse","safeParseAsync","encode","decode","encodeAsync","decodeAsync","safeEncode","safeDecode","safeEncodeAsync","safeDecodeAsync","duration","version","_emoji","date","time","datetime","string","number","_a","inst","util.floatSafeRemainder","util.NUMBER_FORMAT_RANGES","regexes.integer","util.nullish","util.getLengthableOrigin","regexes.lowercase","regexes.uppercase","util.escapeRegex","_a","isAborted","util.aborted","checks","util.explicitlyAborted","core.$ZodAsyncError","checkResult","canary","result","safeParse","safeParseAsync","regexes.string","_","regexes.guid","regexes.uuid","regexes.email","regexes.emoji","regexes.nanoid","regexes.cuid","regexes.cuid2","regexes.ulid","regexes.xid","regexes.ksuid","regexes.datetime","regexes.date","regexes.time","regexes.duration","regexes.ipv4","regexes.ipv6","regexes.cidrv4","regexes.cidrv6","regexes.base64","base64","regexes.base64url","regexes.e164","regexes.number","util.prefixIssues","util.optionalKeys","r","util.cached","isObject","util.isObject","util.esc","allowsEval","util.allowsEval","util.finalizeIssue","core.config","util.cleanRegex","results","left","right","util.isPlainObject","util.getEnumValues","util.escapeRegex","core.$ZodEncodeError","util.issue","meta","util.normalizeParams","checks.$ZodCheckLessThan","checks.$ZodCheckGreaterThan","checks.$ZodCheckMultipleOf","checks.$ZodCheckMaxLength","checks.$ZodCheckMinLength","checks.$ZodCheckLengthEquals","checks.$ZodCheckRegex","checks.$ZodCheckLowerCase","checks.$ZodCheckUpperCase","checks.$ZodCheckIncludes","checks.$ZodCheckStartsWith","checks.$ZodCheckEndsWith","checks.$ZodCheckOverwrite","util.slugify","issue","util.issue","checks.$ZodCheck","describe","meta","_a","meta","id","schema","core._isoDateTime","core._isoDate","core._isoTime","core._isoDuration","core.formatError","core.flattenError","issue","util.jsonStringifyReplacer","issues","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","def","util.mergeDefs","core.clone","meta","checks.overwrite","processors.stringProcessor","checks.regex","checks.includes","checks.startsWith","checks.endsWith","checks.minLength","checks.maxLength","checks.length","checks.lowercase","checks.uppercase","checks.trim","checks.normalize","checks.toLowerCase","checks.toUpperCase","checks.slugify","core._email","core._url","core._jwt","core._emoji","core._guid","core._uuid","core._uuidv4","core._uuidv6","core._uuidv7","core._nanoid","core._cuid","core._cuid2","core._ulid","core._base64","core._base64url","core._xid","core._ksuid","core._ipv4","core._ipv6","core._cidrv4","core._cidrv6","core._e164","iso.datetime","iso.date","iso.time","iso.duration","core._string","processors.numberProcessor","checks.gt","checks.gte","checks.lt","checks.lte","checks.multipleOf","core._number","core._int","processors.unknownProcessor","core._unknown","processors.neverProcessor","core._never","processors.arrayProcessor","core._array","processors.objectProcessor","util.extend","util.safeExtend","util.merge","util.pick","util.omit","util.partial","util.required","util.normalizeParams","processors.unionProcessor","processors.intersectionProcessor","processors.enumProcessor","processors.literalProcessor","processors.transformProcessor","core.$ZodEncodeError","issue","util.issue","output","processors.optionalProcessor","processors.nullableProcessor","processors.defaultProcessor","util.shallowClone","processors.prefaultProcessor","processors.nonoptionalProcessor","processors.catchProcessor","processors.pipeProcessor","processors.readonlyProcessor","processors.customProcessor","core._refine","core._superRefine","core.describe","core.meta","z.object","z.number","z.discriminatedUnion","z.literal","z.string","name","clone","Config: z<Config>","error: unknown","result: SubagentResult","source: (() => Config) | undefined","settingsService: SettingsProvider | undefined","settingsNs: SettingsNamespace | undefined","settingsFailure: string | undefined","config","chunks: Buffer[]","parsed: unknown","name","request: Omit<SubagentStartRequest, 'signal' | 'outputSchema'>"],"sources":["../node_modules/.pnpm/@deepseek-ai+dsh-scope@0.1._6f3351786c779449c277f079a737f571/node_modules/@deepseek-ai/dsh-scope/lib/index.js","../node_modules/.pnpm/@deepseek-ai+dsh-timeout@0._8c173ab999b05cf1db05d479dd44e888/node_modules/@deepseek-ai/dsh-timeout/lib/index.js","../node_modules/.pnpm/@deepseek-ai+dsh-llm@0.1.0-_4ed4e5c71eb965b0bd6912871e829940/node_modules/@deepseek-ai/dsh-llm/lib/index.js","../node_modules/.pnpm/@deepseek-ai+dsh-session@0._959f4648d9537c86268b5de534a89875/node_modules/@deepseek-ai/dsh-session/lib/index.js","../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.1._d489cb013f2a8725198f1fce9da6f626/node_modules/@deepseek-ai/dsh-tools/lib/index.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js","../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js","../node_modules/.pnpm/@deepseek-ai+dsh-subagent@0_3df74c1b55f479c797399aa68ffa64be/node_modules/@deepseek-ai/dsh-subagent/lib/index.js","../node_modules/.pnpm/@deepseek-ai+dsh-settings@0_52495af71738a1095726249ceff4fd7b/node_modules/@deepseek-ai/dsh-settings/lib/index.js","../src/index.ts"],"sourcesContent":["import { Context } from \"@deepseek-ai/cordis\";\n//#region lib/types/store.js\n/**\n* Shared insertion-ordered storage and effect ownership for scope-aware registries.\n*\n* @module @deepseek-ai/dsh-scope\n*/\n/**\n* Insertion-ordered named entries with caller-owned duplicate diagnostics.\n*\n* Values are borrowed. Iterators are live within one nonempty table\n* generation; draining the table detaches them from later insertions. Each\n* successful insertion returns an idempotent undo for that exact entry.\n*/\nvar NamedEntries = class {\n\tduplicateError;\n\tdata = /* @__PURE__ */ new Map();\n\tconstructor(duplicateError) {\n\t\tthis.duplicateError = duplicateError;\n\t}\n\t/**\n\t* Insert one unique name.\n\t* @param name - name unique within this table.\n\t* @param value - borrowed value to retain.\n\t* @returns an idempotent undo that removes only this insertion.\n\t*/\n\tinsert(name, value) {\n\t\tconst data = this.data;\n\t\tif (data.has(name)) throw this.duplicateError(name);\n\t\tdata.set(name, value);\n\t\tlet active = true;\n\t\treturn () => {\n\t\t\tif (!active) return;\n\t\t\tactive = false;\n\t\t\tdata.delete(name);\n\t\t\tif (data.size === 0 && this.data === data) this.data = /* @__PURE__ */ new Map();\n\t\t};\n\t}\n\t/**\n\t* Read one named value.\n\t* @param name - name to resolve.\n\t* @returns the retained value, or `undefined` when absent.\n\t*/\n\tget(name) {\n\t\treturn this.data.get(name);\n\t}\n\t/**\n\t* Test one name for membership.\n\t* @param name - name to test.\n\t* @returns whether the table contains that name.\n\t*/\n\thas(name) {\n\t\treturn this.data.has(name);\n\t}\n\t/**\n\t* Iterate live names in insertion order.\n\t* @returns the native live key iterator.\n\t*/\n\tkeys() {\n\t\treturn this.data.keys();\n\t}\n\t/**\n\t* Iterate live entries in insertion order.\n\t* @returns the native live entry iterator.\n\t*/\n\tentries() {\n\t\treturn this.data.entries();\n\t}\n\t/**\n\t* Iterate live values in insertion order.\n\t* @returns the native live value iterator.\n\t*/\n\tvalues() {\n\t\treturn this.data.values();\n\t}\n\t/**\n\t* Test whether this table has no entries.\n\t* @returns whether the table is empty.\n\t*/\n\tisEmpty() {\n\t\treturn this.data.size === 0;\n\t}\n};\n/**\n* Insertion-ordered anonymous entries with independent registration identity.\n*\n* Equal values remain separate registrations. Values are borrowed, and\n* iterators are live within one nonempty table generation; draining the table\n* detaches them from later appends.\n*/\nvar AnonymousEntries = class {\n\tdata = /* @__PURE__ */ new Map();\n\t/**\n\t* Append one independently owned value.\n\t* @param value - borrowed value to retain.\n\t* @returns an idempotent undo for this exact append.\n\t*/\n\tappend(value) {\n\t\tconst data = this.data;\n\t\tconst key = Symbol();\n\t\tdata.set(key, value);\n\t\tlet active = true;\n\t\treturn () => {\n\t\t\tif (!active) return;\n\t\t\tactive = false;\n\t\t\tdata.delete(key);\n\t\t\tif (data.size === 0 && this.data === data) this.data = /* @__PURE__ */ new Map();\n\t\t};\n\t}\n\t/**\n\t* Iterate live values in insertion order.\n\t* @returns the native live value iterator.\n\t*/\n\tvalues() {\n\t\treturn this.data.values();\n\t}\n\t/**\n\t* Test whether this table has no entries.\n\t* @returns whether the table is empty.\n\t*/\n\tisEmpty() {\n\t\treturn this.data.size === 0;\n\t}\n};\n/**\n* Own the global and exact-scope layers for one registry.\n*\n* Reads never create scoped layers. Registrations derive both visibility and\n* effect ownership from the supplied Cordis context, collect undo before\n* notification, and reclaim only a completely empty aggregate layer.\n*/\nvar ScopedLayers = class {\n\tcreateLayer;\n\tonChange;\n\t/** The eagerly constructed context-global layer. */\n\tglobal;\n\tscoped = /* @__PURE__ */ new Map();\n\tconstructor(createLayer, onChange) {\n\t\tthis.createLayer = createLayer;\n\t\tthis.onChange = onChange;\n\t\tthis.global = createLayer(void 0);\n\t}\n\t/**\n\t* Read an existing exact-scope overlay. Deliberately chain-blind: callers\n\t* addressing one scope's OWN contributions (its restrictions, its guards)\n\t* must not silently pick up an ancestor's — use {@link chainLayers} where\n\t* inheritance is the point.\n\t* @param scope - exact scope key; `undefined` denotes no overlay.\n\t* @returns the existing scoped layer, or `undefined` without creating one.\n\t*/\n\tpeek(scope) {\n\t\tif (scope === void 0) return void 0;\n\t\treturn this.scoped.get(scope);\n\t}\n\t/**\n\t* Existing overlays along the scope's parent chain ({@link scopeChainOf}),\n\t* farthest ancestor first and the exact scope last, so a caller layering\n\t* them in order gives the nearest scope the final word.\n\t* @param scope - viewing scope, or `undefined` for no overlays.\n\t* @returns the existing layers, nearest last; absent overlays are skipped.\n\t*/\n\tchainLayers(scope) {\n\t\tconst layers = [];\n\t\tfor (const key of scopeChainOf(scope).reverse()) {\n\t\t\tconst layer = this.scoped.get(key);\n\t\t\tif (layer !== void 0) layers.push(layer);\n\t\t}\n\t\treturn layers;\n\t}\n\t/**\n\t* Materialize global named entries followed by scope-chain shadows,\n\t* farthest ancestor first, so the nearest scope's entry wins a name.\n\t* @param scope - viewing scope, or `undefined` for the global view.\n\t* @param pick - select the named table from a layer.\n\t* @returns an insertion-ordered effective map.\n\t*/\n\tmerge(scope, pick) {\n\t\tconst merged = new Map(pick(this.global).entries());\n\t\tfor (const layer of this.chainLayers(scope)) for (const [name, value] of pick(layer).entries()) merged.set(name, value);\n\t\treturn merged;\n\t}\n\t/**\n\t* Attach one synchronous layer mutation to its registration context.\n\t* @param ctx - context that determines both scope visibility and effect ownership.\n\t* @param action - atomic mutation returning its synchronous undo.\n\t* @param options - Cordis effect label and optional change notification.\n\t* @returns the exact disposer returned by `ctx.effect()`.\n\t*/\n\teffect(ctx, action, options) {\n\t\tconst scope = scopeOf(ctx);\n\t\tconst notify = options.notify ?? true;\n\t\treturn ctx.effect(function* () {\n\t\t\tlet layer;\n\t\t\tlet created = false;\n\t\t\tif (scope === void 0) layer = this.global;\n\t\t\telse {\n\t\t\t\tconst existing = this.scoped.get(scope);\n\t\t\t\tif (existing === void 0) {\n\t\t\t\t\tlayer = this.createLayer(scope);\n\t\t\t\t\tthis.scoped.set(scope, layer);\n\t\t\t\t\tcreated = true;\n\t\t\t\t} else layer = existing;\n\t\t\t}\n\t\t\tlet undo;\n\t\t\ttry {\n\t\t\t\tundo = action(layer);\n\t\t\t} catch (error) {\n\t\t\t\tif (scope !== void 0 && created && layer.isEmpty()) this.scoped.delete(scope);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tyield () => {\n\t\t\t\tundo();\n\t\t\t\tif (scope !== void 0 && layer.isEmpty()) this.scoped.delete(scope);\n\t\t\t\tif (notify) this.onChange();\n\t\t\t};\n\t\t\tif (notify) this.onChange();\n\t\t}.bind(this), options.label);\n\t}\n};\n//#endregion\n//#region lib/types/index.js\n/**\n* Scoped-context primitive: mint a Cordis context that tags registrations with\n* an opaque identity and build routing-only event carriers for that identity.\n*\n* @module @deepseek-ai/dsh-scope\n*/\n/** Context tag written by {@link createScope}. */\nconst kScope = Symbol(\"dsh.scope\");\n/** The key associated with each carrier. Presence distinguishes an unkeyed carrier from a non-carrier. */\nconst carrierKeys = /* @__PURE__ */ new WeakMap();\n/**\n* The enclosing scope of each key. One relation powers both directions of\n* scope nesting: registration views inherit DOWN the chain (a child scope\n* sees its ancestors' layers — {@link ScopedLayers}), and event admission\n* extends UP it (a listener tagged with an ancestor receives events dispatched\n* to a descendant key — {@link scopeTarget}).\n*/\nconst scopeParents = /* @__PURE__ */ new WeakMap();\n/** Cycle-checked write shared by the bind and every rebind. */\nfunction linkScopeParent(key, parent) {\n\tfor (let cursor = parent; cursor !== void 0; cursor = scopeParents.get(cursor)) if (cursor === key) throw new Error(\"dsh-scope: scope parent link would form a cycle\");\n\tscopeParents.set(key, parent);\n}\n/**\n* Bind `parent` as `key`'s enclosing scope, once.\n*\n* A key that already has a parent throws: there is no open re-link path, so a\n* scope's ancestry cannot be moved by anyone but the original binder, who\n* alone receives the {@link ScopeParentBinding}. A link that would close a\n* cycle is rejected, because every chain consumer walks parents to the root.\n* @param key - the child scope key.\n* @param parent - its enclosing scope key.\n* @returns the binding that alone may re-link this key.\n*/\nfunction bindScopeParent(key, parent) {\n\tif (scopeParents.has(key)) throw new Error(\"dsh-scope: scope key is already bound to a parent; re-linking requires the binding returned by the original bind\");\n\tlinkScopeParent(key, parent);\n\treturn { rebind(next) {\n\t\tlinkScopeParent(key, next);\n\t} };\n}\n/**\n* Read one key's enclosing scope.\n* @param key - the scope key to inspect.\n* @returns its parent key, or `undefined` for a root scope.\n*/\nfunction scopeParentOf(key) {\n\treturn scopeParents.get(key);\n}\n/**\n* The chain from a key to its root ancestor.\n* @param key - the starting key, or `undefined` for the empty chain.\n* @returns keys nearest-first: `[key, parent, grandparent, …]`.\n*/\nfunction scopeChainOf(key) {\n\tconst chain = [];\n\tfor (let cursor = key; cursor !== void 0; cursor = scopeParents.get(cursor)) chain.push(cursor);\n\treturn chain;\n}\n/** Follow a Cordis fiber through asynchronous teardown even if its raw disposer was already claimed. */\nasync function quiesceFiber(fiber) {\n\tawait Promise.resolve(fiber.dispose());\n\twhile (fiber.inertia !== void 0) await fiber.inertia;\n}\n/** Shared no-op plugin used as the backing scope fiber. */\nfunction scope() {}\n/**\n* Mint a scope under `ctx`. The scoped context inherits the minting plugin's\n* dependency API and owns every registration made through it.\n* @param ctx - active context whose dependency API the scope inherits.\n* @param key - opaque identity used for listener routing.\n* @param options - optional scope-chain placement.\n* @returns the scoped context and exact/shared disposal boundaries.\n*/\nfunction createScope(ctx, key, options) {\n\tif (options?.parent !== void 0) bindScopeParent(key, options.parent);\n\tconst fiber = ctx.plugin(scope);\n\tconst scoped = fiber.ctx.extend({ [kScope]: key });\n\tlet disposing;\n\treturn {\n\t\tctx: scoped,\n\t\trawDispose: fiber.dispose,\n\t\tdispose: () => disposing ??= quiesceFiber(fiber)\n\t};\n}\n/**\n* Read the nearest scope tag inherited by a context.\n* @param ctx - context to inspect.\n* @returns its scope key, or `undefined` for an unscoped context.\n*/\nfunction scopeOf(ctx) {\n\treturn ctx[kScope];\n}\n/**\n* Build an opaque receiver that preserves the base filter, admits untagged\n* listeners globally, and admits tagged listeners for a matching key or any\n* of its ancestors ({@link bindScopeParent}): a listener owned by an enclosing\n* scope receives every descendant scope's events, which is what lets one\n* standing composition observe each of the agents composed under it. A tag\n* BELOW the dispatch key stays excluded — events flow up the chain, never\n* down.\n* @param base - subject or service whose existing Cordis filter is preserved.\n* @param key - routed scope identity, or `undefined` for an unscoped subject.\n* @returns a carrier whose subject remains available only through event arguments.\n*/\nfunction scopeTarget(base, key) {\n\tconst baseFilter = base[Context.filter];\n\tconst carrier = { [Context.filter](ctx) {\n\t\tif (baseFilter !== void 0 && !baseFilter.call(base, ctx)) return false;\n\t\tconst tag = scopeOf(ctx);\n\t\tif (tag === void 0) return true;\n\t\tfor (let cursor = key; cursor !== void 0; cursor = scopeParents.get(cursor)) if (cursor === tag) return true;\n\t\treturn false;\n\t} };\n\tcarrierKeys.set(carrier, key);\n\treturn carrier;\n}\n/**\n* Test whether a value is a scope carrier.\n* @param value - dispatch receiver to inspect.\n* @returns whether {@link scopeTarget} created it.\n*/\nfunction isScopeCarrier(value) {\n\treturn typeof value === \"object\" && value !== null && carrierKeys.has(value);\n}\n/**\n* Read a carrier's routing key.\n* @param value - dispatch receiver to inspect.\n* @returns the carrier key, or `undefined` for an unkeyed/non-carrier value.\n*/\nfunction carrierKeyOf(value) {\n\tif (!isScopeCarrier(value)) return void 0;\n\treturn carrierKeys.get(value);\n}\n//#endregion\nexport { AnonymousEntries, NamedEntries, ScopedLayers, bindScopeParent, carrierKeyOf, createScope, isScopeCarrier, scopeChainOf, scopeOf, scopeParentOf, scopeTarget };\n","//#region lib/types/index.js\n/**\n* Shared timeout arithmetic, signal fusion, and classification. The library\n* only notifies through abort signals; each capability still owns the mechanism\n* that stops its work and translates timeout reasons into public outcomes.\n* @module @deepseek-ai/dsh-timeout\n*/\n/**\n* Internal abort reason carrying a capability-owned code and elapsed deadline.\n* Providers translate it through {@link timeoutOf} before returning to callers.\n*/\nvar TimeoutReason = class extends Error {\n\tcode;\n\ttimeoutMs;\n\tname = \"TimeoutReason\";\n\t/**\n\t* @param code Capability-owned timeout code (e.g. `BASH_TIMEOUT`).\n\t* @param timeoutMs The deadline that elapsed, in milliseconds.\n\t*/\n\tconstructor(code, timeoutMs) {\n\t\tsuper(`${code} after ${timeoutMs}ms`);\n\t\tthis.code = code;\n\t\tthis.timeoutMs = timeoutMs;\n\t}\n};\n/** Largest delay Node schedules without clamping it to one millisecond. */\nconst MAX_TIMER_DELAY_MS = 2147483647;\nfunction assertTimerDelay(timeoutMs, name) {\n\tif (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw new Error(`${name} must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);\n}\n/**\n* Validate a caller's optional timeout hint, use the backend default, then cap\n* it. Supplied values must be positive and finite; zero is not a public\n* disable-timeout sentinel.\n*\n* @param requested The caller's optional hint; validated when present.\n* @param def The backend default applied when `requested` is absent.\n* @param max The backend upper bound the result is capped to.\n* @param name Field name used in the thrown message (so the caller sees which input was\n* bad).\n* @returns The effective timeout in milliseconds: `min(requested ?? def, max)`.\n*/\nfunction clampTimeout(requested, def, max, name = \"timeoutMs\") {\n\tif (requested !== void 0 && (!Number.isFinite(requested) || requested <= 0)) throw new Error(`${name} must be a positive finite number`);\n\treturn Math.min(requested ?? def, max);\n}\n/**\n* Fuse upstream cancellation with an identifiable timeout. `timeoutMs <= 0` is\n* the internal no-timer sentinel; the returned disposer clears an armed timer.\n* The signal only notifies, so callers must stop their own work.\n*\n* @param upstream The caller's cancellation signal, if any, fused into the result.\n* @param timeoutMs Deadline in milliseconds; `<= 0` means \"no timeout\" (arm no timer).\n* @param code Capability-owned code stamped onto the timeout's {@link TimeoutReason}.\n* @returns The fused {@link Deadline} (signal + timer cleanup).\n*/\nfunction deadline(upstream, timeoutMs, code) {\n\tif (timeoutMs <= 0) return {\n\t\tsignal: upstream ?? new AbortController().signal,\n\t\t[Symbol.dispose]() {}\n\t};\n\tassertTimerDelay(timeoutMs, \"deadline timeoutMs\");\n\tconst timer = new AbortController();\n\tconst id = setTimeout(() => {\n\t\ttimer.abort(new TimeoutReason(code, timeoutMs));\n\t}, timeoutMs);\n\treturn {\n\t\tsignal: upstream !== void 0 ? AbortSignal.any([upstream, timer.signal]) : timer.signal,\n\t\t[Symbol.dispose]() {\n\t\t\tclearTimeout(id);\n\t\t}\n\t};\n}\n/**\n* Create a rearmable idle watchdog for an async iterator. The timer exists only\n* while {@link IdleWatchdog.next} is outstanding, so consumer think time does\n* not count as provider idle time. The returned signal is stable for the whole\n* call and only notifies; the iterator must observe it to terminate its work.\n*\n* @param upstream - caller cancellation fused into the stable signal.\n* @param timeoutMs - positive finite idle interval in milliseconds.\n* @param code - capability-owned code carried by the timeout reason.\n* @returns a stable signal, guarded next operation, and timer disposer.\n*/\nfunction idleWatchdog(upstream, timeoutMs, code) {\n\tassertTimerDelay(timeoutMs, \"idleWatchdog timeoutMs\");\n\tconst timeout = new AbortController();\n\tconst signal = upstream === void 0 ? timeout.signal : AbortSignal.any([upstream, timeout.signal]);\n\tlet timer;\n\tlet outstanding = false;\n\tlet disposed = false;\n\tconst arm = () => {\n\t\tif (timer !== void 0) clearTimeout(timer);\n\t\ttimer = setTimeout(() => {\n\t\t\ttimeout.abort(new TimeoutReason(code, timeoutMs));\n\t\t}, timeoutMs);\n\t};\n\treturn {\n\t\tsignal,\n\t\tasync next(iterator) {\n\t\t\tif (disposed) throw new Error(\"idleWatchdog is disposed\");\n\t\t\tif (outstanding) throw new Error(\"idleWatchdog next is already outstanding\");\n\t\t\toutstanding = true;\n\t\t\tarm();\n\t\t\ttry {\n\t\t\t\treturn await iterator.next();\n\t\t\t} finally {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\ttimer = void 0;\n\t\t\t\toutstanding = false;\n\t\t\t}\n\t\t},\n\t\tpulse() {\n\t\t\tif (disposed || !outstanding) return;\n\t\t\tarm();\n\t\t},\n\t\t[Symbol.dispose]() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tif (timer !== void 0) clearTimeout(timer);\n\t\t\ttimer = void 0;\n\t\t}\n\t};\n}\n/**\n* Recover a timeout reason from a reason-bearing object. Supplying `code`\n* distinguishes this deadline from a nested upstream deadline; a foreign code\n* follows the ordinary cancellation path.\n*\n* @param x An {@link AbortSignal} or any `{ reason }` carrier (e.g. a caught abort error).\n* @param code When provided, only a {@link TimeoutReason} with this exact `code` matches.\n* @returns The matching {@link TimeoutReason}, else `undefined`.\n*/\nfunction timeoutOf(x, code) {\n\tconst reason = x.reason;\n\tif (!(reason instanceof TimeoutReason)) return void 0;\n\treturn code === void 0 || reason.code === code ? reason : void 0;\n}\n//#endregion\nexport { MAX_TIMER_DELAY_MS, TimeoutReason, clampTimeout, deadline, idleWatchdog, timeoutOf };\n","import { createRequire } from \"node:module\";\nimport { Service } from \"@deepseek-ai/cordis\";\nimport z from \"@deepseek-ai/schemastery\";\nimport { MAX_TIMER_DELAY_MS } from \"@deepseek-ai/dsh-timeout\";\n//#region lib/types/brand.js\n/**\n* dsh-llm's owned branded ids: tool-call correlation and provider request\n* diagnostics.\n*\n* The `Branded<B>` primitive itself lives in `@deepseek-ai/dsh-brand` (a\n* zero-dependency type-only package) so every owner of a cross-boundary id can\n* brand it without depending on dsh-llm; see that package's README for the\n* nominal-typing policy.\n*\n* @module @deepseek-ai/dsh-llm/brand\n*/\n/**\n* Brand a message identifier.\n* @param id - the opaque message identifier.\n* @returns the same string, branded; no validation is performed.\n*/\nfunction MessageId(id) {\n\treturn id;\n}\n/**\n* Brand a string as a {@link CallId}.\n* @param id - the provider-issued (or synthesized) call id.\n* @returns the same string, branded; no validation is performed.\n*/\nfunction CallId(id) {\n\treturn id;\n}\n/**\n* Brand a provider-issued request identifier.\n* @param id - the opaque provider-issued string.\n* @returns the same string, branded; no validation is performed.\n*/\nfunction ProviderRequestId(id) {\n\treturn id;\n}\n/**\n* Brand an adapter-owned reasoning-effort identifier.\n* @param id - the opaque identifier exposed by one model capability.\n* @returns the same string, branded; no validation is performed.\n*/\nfunction ReasoningEffortId(id) {\n\treturn id;\n}\n//#endregion\n//#region lib/types/call-config.js\n/**\n* Conversation call configuration and freeze utilities. Provider routing,\n* model, reasoning effort, and sampling values are request-header state that\n* can affect cache reuse; request waterfalls replace them and the loop logs\n* changed snapshots instead of allowing silent per-call drift.\n* @module dsh-llm/call-config\n*/\n/** Process-local identities of request objects assembled by dsh-agent-loop. */\nconst AGENT_LOOP_REQUESTS = /* @__PURE__ */ new WeakSet();\n/**\n* Field-wise equality over {@link LlmCallConfig} — the comparison a caller\n* runs to decide whether a proposed configuration is a real change (worth a\n* logged header snapshot) or the held one restated.\n* @param a - one configuration.\n* @param b - the other.\n* @returns whether every field (including the `stop` list, element-wise) matches.\n*/\nfunction callConfigEquals(a, b) {\n\tif (a.provider !== b.provider || a.model !== b.model || a.reasoningEffort !== b.reasoningEffort || a.temperature !== b.temperature || a.maxTokens !== b.maxTokens) return false;\n\tif (a.stop === void 0 || b.stop === void 0) return a.stop === b.stop;\n\treturn a.stop.length === b.stop.length && a.stop.every((s, i) => s === b.stop?.[i]);\n}\n/**\n* Mark one exact request object as assembled by dsh-agent-loop.\n* @param request - loop-owned request envelope before LLM dispatch.\n* @returns the same request object marked as created by the process-local agent loop.\n*/\nfunction markAgentLoopRequest(request) {\n\tAGENT_LOOP_REQUESTS.add(request);\n\treturn request;\n}\n/**\n* Test whether the exact request object was assembled by dsh-agent-loop.\n* @param request - request envelope observed at the LLM waterfall.\n* @returns whether {@link markAgentLoopRequest} recorded this object.\n*/\nfunction isAgentLoopRequest(request) {\n\treturn AGENT_LOOP_REQUESTS.has(request);\n}\n/**\n* Deep-freeze a value in place with an iterative traversal, guarding cycles,\n* so later mutation throws without imposing a JavaScript call-stack depth cap.\n* {@link AbortSignal} objects are deliberately skipped because they are the\n* request's live cancellation channel and freezing them breaks abort.\n* @param value - the value to freeze in place.\n* @returns the same value, frozen.\n*/\nfunction deepFreeze(value) {\n\tconst seen = /* @__PURE__ */ new WeakSet();\n\tconst pending = [{\n\t\tkind: \"visit\",\n\t\tnode: value\n\t}];\n\twhile (pending.length > 0) {\n\t\tconst task = pending.pop();\n\t\t/* v8 ignore next -- the loop condition guarantees one pending task. */\n\t\tif (task === void 0) continue;\n\t\tif (task.kind === \"property\") {\n\t\t\tpending.push({\n\t\t\t\tkind: \"visit\",\n\t\t\t\tnode: task.source[task.key]\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst node = task.node;\n\t\tif (node === null || typeof node !== \"object\") continue;\n\t\tif (node instanceof AbortSignal) continue;\n\t\tif (seen.has(node)) continue;\n\t\tseen.add(node);\n\t\tObject.freeze(node);\n\t\tconst keys = Object.keys(node);\n\t\tfor (let index = keys.length - 1; index >= 0; index--) {\n\t\t\tconst key = keys[index];\n\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\tif (key === void 0) continue;\n\t\t\tpending.push({\n\t\t\t\tkind: \"property\",\n\t\t\t\tsource: node,\n\t\t\t\tkey\n\t\t\t});\n\t\t}\n\t}\n\treturn value;\n}\n//#endregion\n//#region lib/types/message.js\n/** Message value types, identity, and immutable construction helpers. */\n/**\n* Bound for a `notice` summary. The account rides a collapsed transcript row\n* and is committed to the durable log, while its inputs — task labels, goal\n* objectives, tool arguments — are caller text with no length of their own.\n*/\nconst CONTEXT_SUMMARY_MAX_CHARS = 120;\n/**\n* Bound one `notice` summary to {@link CONTEXT_SUMMARY_MAX_CHARS}.\n* @param summary - the producer's one-line account, of any length.\n* @returns the account, ellipsized when it exceeds the bound.\n*/\nfunction boundContextSummary(summary) {\n\treturn summary.length <= 120 ? summary : `${summary.slice(0, 119)}…`;\n}\n/**\n* Detach and deep-freeze a message whose identity already exists.\n* @param message - complete message, including its stable identity.\n* @returns an immutable snapshot that preserves the identity.\n*/\nfunction freezeMessage(message) {\n\treturn deepFreeze(structuredClone(message));\n}\n/**\n* Create one identified message and freeze it before publication.\n* @param input - complete role, content, and source for a new message.\n* @returns an immutable message with a fresh stable identity.\n*/\nfunction createMessage(input) {\n\treturn freezeMessage({\n\t\t...input,\n\t\tid: MessageId(crypto.randomUUID())\n\t});\n}\n/**\n* Create one identified user-role message and freeze it before publication.\n* @param input - complete content and source for a new user message.\n* @returns an immutable user message with a fresh stable identity.\n*/\nfunction createUserMessage(input) {\n\treturn createMessage({\n\t\t...input,\n\t\trole: \"user\"\n\t});\n}\n/**\n* Create one identified model-produced assistant message and freeze it before publication.\n* @param input - complete content plus the provider, model, and optional replay state for a new assistant message.\n* @returns an immutable assistant message with fixed role/source tags and a fresh stable identity.\n*/\nfunction createAssistantMessage(input) {\n\treturn createMessage({\n\t\trole: \"assistant\",\n\t\tcontent: input.content,\n\t\tsource: {\n\t\t\tkind: \"model\",\n\t\t\t...input.source\n\t\t}\n\t});\n}\n/**\n* Create and freeze one identified tool-result message.\n* @param input - call identity, raw result blocks, and outcome.\n* @returns an immutable user-role tool-result message.\n*/\nfunction createToolResultMessage(input) {\n\treturn createUserMessage({\n\t\tsource: {\n\t\t\tkind: \"tool\",\n\t\t\tcallId: input.callId\n\t\t},\n\t\tcontent: [{\n\t\t\ttype: \"tool-result\",\n\t\t\ttoolCallId: input.callId,\n\t\t\tcontent: input.content,\n\t\t\tisError: input.isError\n\t\t}]\n\t});\n}\n/**\n* Whether a stream chunk carries visible model output (the first-token\n* boundary shared by client step timing and the whole-log sessionStats\n* projection). Empty deltas (heartbeats, empty tool-call frames) do not count\n* as a first token.\n* @param chunk - the stream chunk to test.\n* @returns true when the chunk contains a non-empty text/reasoning/tool delta.\n*/\nfunction isTokenDelta(chunk) {\n\tswitch (chunk.type) {\n\t\tcase \"text-delta\":\n\t\tcase \"reasoning-delta\": return chunk.text !== \"\";\n\t\tcase \"tool-call-delta\": return chunk.argumentsDelta !== \"\" || chunk.name !== void 0;\n\t\tdefault: return false;\n\t}\n}\n//#endregion\n//#region lib/types/error.js\n/**\n* Harness error base with a stable machine-routable code and chained cause.\n* Package errors extend it so tool results and replay can retain failure class.\n* @module @deepseek-ai/dsh-llm/error\n*/\n/**\n* Base class for all harness errors. Carries a `code` (stable, programmatic —\n* e.g. `NO_ADAPTER`, `INVALID_ARGS`, `INVARIANT`) distinct from the\n* human-readable `message`, and supports `cause` chaining via the standard\n* `ErrorOptions`. `name` defaults to the subclass constructor name.\n*/\nvar HarnessError = class extends Error {\n\t/** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */\n\tcode;\n\tconstructor(message, code, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = new.target.name;\n\t}\n};\n/** Canonical provider-neutral code for a model request rejected because its context window was exceeded. */\nconst CONTEXT_WINDOW_EXCEEDED_CODE = \"CONTEXT_WINDOW_EXCEEDED\";\n/** Canonical provider-neutral code for an exhausted account quota or balance. */\nconst QUOTA_EXCEEDED_CODE = \"QUOTA\";\n/**\n* Canonical provider-neutral code for a response that completed normally but\n* carried no content blocks at all. Providers occasionally emit a degenerate\n* completion (a terminal stop with zero output); adapters classify it as this\n* failure instead of yielding an empty assistant message, because an empty\n* message silently ends the turn with nothing for the user or the loop to act\n* on. The attempt produced nothing durable, so retry policy treats it as safe\n* to repeat.\n*/\nconst EMPTY_RESPONSE_CODE = \"EMPTY_RESPONSE\";\n/**\n* Canonical provider-neutral code for a credential that was supplied but\n* cannot be used — malformed rather than absent. Distinct from\n* `MISSING_CREDENTIAL` because the fix differs: correct the stored value\n* rather than supply one. Deliberately outside the default retryable set —\n* a malformed credential fails identically on every attempt.\n*/\nconst INVALID_CREDENTIAL_CODE = \"INVALID_CREDENTIAL\";\n/** Structured codes and plain phrases that explicitly name a context bound being exceeded. */\nconst STRUCTURED_CONTEXT_OVERFLOW = new RegExp(String.raw`(?:^|[^a-z0-9])context[\\s_-](?:length|window)[\\s_-]` + String.raw`(?:exceed(?:ed|s)?|overflow(?:ed)?|limit[\\s_-]exceeded)(?:$|[^a-z0-9])`, \"i\");\n/** Request-size wording that ties \"too large\" directly to model context capacity. */\nconst TOO_LARGE_FOR_CONTEXT = new RegExp(String.raw`\\b(?:request|prompt|input|messages?)\\s+(?:is\\s+|are\\s+)?` + String.raw`too\\s+(?:large|long)\\s+for\\s+(?:(?:this|the)\\s+)?` + String.raw`(?:model(?:'s)?\\s+)?context(?:\\s+window)?\\b`, \"i\");\n/** \"Exceeds\" wording is safe only when its object is explicitly the model context. */\nconst EXCEEDS_MODEL_CONTEXT = new RegExp(String.raw`\\b(?:input|prompt|request|messages?)\\b.{0,40}` + String.raw`\\b(?:exceed(?:s|ed)?|overflows?|is\\s+larger\\s+than)\\b.{0,40}` + String.raw`\\b(?:the\\s+)?(?:model(?:'s)?\\s+)?context(?:\\s+(?:length|window))?\\b`, \"i\");\n/**\n* Recognize the context-overflow wording used by OpenAI-compatible providers\n* and library adapters. Adapters pass all available provider code, type, and\n* message text so both thrown and in-band delivery styles share one classifier.\n* @param detail - provider error code/type/message text joined into one string.\n* @returns true when the detail identifies a request exceeding the model context window.\n*/\nfunction isContextWindowExceededError(detail) {\n\treturn STRUCTURED_CONTEXT_OVERFLOW.test(detail) || /\\b(?:maximum|max)(?:\\s+(?:allowed|supported))?\\s+context\\s+(?:length|window)\\b/i.test(detail) || TOO_LARGE_FOR_CONTEXT.test(detail) || /\\b(?:input|prompt|request)\\s+(?:is\\s+)?too\\s+(?:long|large)\\s+for\\s+(?:this|the)\\s+model\\b/i.test(detail) || EXCEEDS_MODEL_CONTEXT.test(detail);\n}\n/**\n* Recognize provider wording that identifies an exhausted account quota rather\n* than a transient request-rate limit.\n* @param detail - provider error code/type/message text joined into one string.\n* @returns true only for terminal quota, balance, credit, budget, or usage-limit wording.\n*/\nfunction isQuotaExceededError(detail) {\n\treturn /\\binsufficient[\\s_-]+(?:quota|balance|credits?)\\b/i.test(detail) || /\\b(?:quota|usage[\\s_-]+limit)[\\s_-]+(?:exceeded|exhausted|reached)\\b/i.test(detail) || /\\bexceed(?:ed|s)?[\\s_-]+(?:(?:your|the)[\\s_-]+)?(?:current[\\s_-]+)?quota\\b/i.test(detail) || /\\b(?:balance|credits?)[\\s_-]+(?:exhausted|depleted)\\b/i.test(detail) || /\\bout[\\s_-]+of[\\s_-]+(?:credits?|budget)\\b/i.test(detail);\n}\n/**\n* Render a thrown value with its full `cause` chain and AggregateError\n* members, so transport wrappers like undici's `TypeError: fetch failed`\n* surface the underlying failure instead of masking it. Plain structured\n* failures render their own data-backed `message`. Diagnostic-surface\n* rendering only (messages, notices, logs) — never parse the result; route on\n* {@link HarnessError.code}.\n* @param value - the caught value (`unknown` in catch clauses).\n* @returns the outermost message first, each cause appended with `: ` (skipped\n* when it repeats the wrapper message verbatim), and AggregateError members\n* bracketed and `; `-joined.\n*/\nfunction errorChain(value) {\n\tconst path = /* @__PURE__ */ new Set();\n\tconst render = (current) => {\n\t\tif (path.has(current)) return \"<circular cause>\";\n\t\tpath.add(current);\n\t\ttry {\n\t\t\tif (!(current instanceof Error)) {\n\t\t\t\tif (typeof current === \"object\" && current !== null) {\n\t\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(current, \"message\");\n\t\t\t\t\tif (descriptor !== void 0 && \"value\" in descriptor && typeof descriptor.value === \"string\") return descriptor.value;\n\t\t\t\t}\n\t\t\t\treturn String(current);\n\t\t\t}\n\t\t\tconst message = current.message === \"\" ? current.name : current.message;\n\t\t\tconst members = current instanceof AggregateError && current.errors.length > 0 ? ` [${current.errors.map(render).join(\"; \")}]` : \"\";\n\t\t\tconst causeText = current.cause === void 0 || current.cause === null ? \"\" : render(current.cause);\n\t\t\treturn `${message}${members}${causeText === \"\" || causeText === message ? \"\" : `: ${causeText}`}`;\n\t\t} catch {\n\t\t\treturn \"<unrenderable value>\";\n\t\t} finally {\n\t\t\tpath.delete(current);\n\t\t}\n\t};\n\treturn render(value);\n}\n/**\n* Narrow an arbitrary thrown value to a HarnessError (for `instanceof` at runtime boundaries).\n* @param value - the caught value (`unknown` in catch clauses).\n* @returns true only for real instances; duck-typed or cross-realm errors do not narrow.\n*/\nfunction isHarnessError(value) {\n\treturn value instanceof HarnessError;\n}\n//#endregion\n//#region lib/types/retry-policy.js\n/**\n* Provider-owned request-retry policy configuration and resolution.\n*\n* Adapters expose one resolved policy per registered provider route; the\n* optional dsh-llm-retry plugin executes it on the agent's failed-step extension point.\n*\n* @module @deepseek-ai/dsh-llm/retry-policy\n*/\nconst DEFAULT_MAX_RETRIES = 2;\nconst DEFAULT_INITIAL_DELAY_MS = 500;\nconst DEFAULT_MAX_DELAY_MS = 1e4;\nconst DEFAULT_JITTER_RATIO = .1;\nconst DEFAULT_RETRYABLE_CODES = Object.freeze([\n\tEMPTY_RESPONSE_CODE,\n\t\"RATE_LIMIT\",\n\t\"SERVER\",\n\t\"TIMEOUT\",\n\t\"TRANSPORT\"\n]);\nconst backoffSchema = z.object({\n\tinitialDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),\n\tmaxDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),\n\tjitterRatio: z.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)\n});\nconst normalPolicySchema = z.object({\n\tmode: z.const(\"normal\").required(),\n\tmaxRetries: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),\n\tretryableCodes: z.array(z.string()).default([...DEFAULT_RETRYABLE_CODES]),\n\tbackoff: backoffSchema\n});\nconst alwaysPolicySchema = z.object({\n\tmode: z.const(\"always\").required(),\n\tbackoff: backoffSchema\n});\n/** Cordis schema embedded by each concrete provider configuration. */\nconst RetryPolicySchema = z.union([normalPolicySchema, alwaysPolicySchema]);\nconst NORMAL_POLICY_KEYS = new Set([\n\t\"mode\",\n\t\"maxRetries\",\n\t\"retryableCodes\",\n\t\"backoff\"\n]);\nconst ALWAYS_POLICY_KEYS = new Set([\"mode\", \"backoff\"]);\nconst BACKOFF_KEYS = new Set([\n\t\"initialDelayMs\",\n\t\"maxDelayMs\",\n\t\"jitterRatio\"\n]);\nfunction validateKeys(value, allowed, path) {\n\tfor (const key of Object.keys(value)) if (!allowed.has(key)) throw new Error(`${path}: unknown key \"${key}\"`);\n}\nfunction resolveBackoff(config, path) {\n\tif (config !== void 0) validateKeys(config, BACKOFF_KEYS, path);\n\tconst initialDelayMs = config?.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n\tconst maxDelayMs = config?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n\tconst jitterRatio = config?.jitterRatio ?? DEFAULT_JITTER_RATIO;\n\tif (!Number.isFinite(initialDelayMs) || initialDelayMs <= 0 || initialDelayMs > MAX_TIMER_DELAY_MS) throw new Error(`${path}.initialDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);\n\tif (!Number.isFinite(maxDelayMs) || maxDelayMs <= 0 || maxDelayMs > MAX_TIMER_DELAY_MS) throw new Error(`${path}.maxDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);\n\tif (initialDelayMs > maxDelayMs) throw new Error(`${path}.initialDelayMs must be less than or equal to maxDelayMs`);\n\tif (!Number.isFinite(jitterRatio) || jitterRatio < 0 || jitterRatio > 1) throw new Error(`${path}.jitterRatio must be between 0 and 1`);\n\treturn Object.freeze({\n\t\tinitialDelayMs,\n\t\tmaxDelayMs,\n\t\tjitterRatio\n\t});\n}\n/**\n* Validate, default, and detach one provider-owned retry policy.\n* @param config - optional provider configuration; omission selects normal defaults.\n* @param path - diagnostic path naming the provider config that owns the value.\n* @returns an immutable policy safe to capture in provider registration state.\n*/\nfunction resolveRetryPolicy(config, path) {\n\tif (config === void 0) return Object.freeze({\n\t\tmode: \"normal\",\n\t\tmaxRetries: DEFAULT_MAX_RETRIES,\n\t\tretryableCodes: DEFAULT_RETRYABLE_CODES,\n\t\t...resolveBackoff(void 0, `${path}.backoff`)\n\t});\n\tswitch (config.mode) {\n\t\tcase \"normal\": {\n\t\t\tvalidateKeys(config, NORMAL_POLICY_KEYS, path);\n\t\t\tconst maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;\n\t\t\tconst retryableCodes = config.retryableCodes ?? [...DEFAULT_RETRYABLE_CODES];\n\t\t\tif (!Number.isSafeInteger(maxRetries) || maxRetries < 0) throw new Error(`${path}.maxRetries must be a non-negative safe integer`);\n\t\t\tif (retryableCodes.length === 0) throw new Error(`${path}.retryableCodes must not be empty`);\n\t\t\tif (retryableCodes.some((code) => typeof code !== \"string\" || code.length === 0)) throw new Error(`${path}.retryableCodes must contain only non-empty strings`);\n\t\t\tif (new Set(retryableCodes).size !== retryableCodes.length) throw new Error(`${path}.retryableCodes must not contain duplicates`);\n\t\t\treturn Object.freeze({\n\t\t\t\tmode: \"normal\",\n\t\t\t\tmaxRetries,\n\t\t\t\tretryableCodes: Object.freeze([...retryableCodes]),\n\t\t\t\t...resolveBackoff(config.backoff, `${path}.backoff`)\n\t\t\t});\n\t\t}\n\t\tcase \"always\":\n\t\t\tvalidateKeys(config, ALWAYS_POLICY_KEYS, path);\n\t\t\treturn Object.freeze({\n\t\t\t\tmode: \"always\",\n\t\t\t\t...resolveBackoff(config.backoff, `${path}.backoff`)\n\t\t\t});\n\t\tdefault: throw new Error(`${path}.mode must be \"normal\" or \"always\"`);\n\t}\n}\n//#endregion\n//#region lib/types/adapter-failure.js\n/**\n* Normalization for values thrown by a final LLM adapter boundary.\n*\n* @module @deepseek-ai/dsh-llm/adapter-failure\n*/\n/**\n* Detach serializable provider facts from a value thrown by an adapter.\n* @param value - arbitrary value thrown during adapter dispatch or iteration.\n* @returns immutable provider-neutral facts suitable for a terminal finish chunk.\n* @internal\n*/\nfunction normalizeLlmFailure(value) {\n\tconst error = value instanceof Error ? value : new HarnessError(thrownMessage(value), \"UNKNOWN\", { cause: value });\n\tconst carried = ownFailureSnapshot(error);\n\tif (carried !== void 0 && carried.code === ownErrorCode(error)) return carried;\n\treturn Object.freeze({\n\t\tmessage: errorMessage(error),\n\t\tcode: harnessErrorCode(error)\n\t});\n}\n/** Render a non-Error throw without letting hostile coercion escape normalization. */\nfunction thrownMessage(value) {\n\ttry {\n\t\tconst message = String(value);\n\t\treturn message.length > 0 ? message : \"LLM adapter failed\";\n\t} catch (_hostileThrownValue) {\n\t\treturn \"LLM adapter failed\";\n\t}\n}\n/** Read a foreign error's own data-backed `code` without invoking accessors. */\nfunction ownErrorCode(error) {\n\ttry {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(error, \"code\");\n\t\treturn descriptor !== void 0 && \"value\" in descriptor ? descriptor.value : void 0;\n\t} catch (_sdkPropertyTrap) {\n\t\treturn;\n\t}\n}\n/** Snapshot an own data property without invoking an SDK-defined accessor. */\nfunction ownFailureSnapshot(error) {\n\ttry {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(error, \"failure\");\n\t\treturn descriptor !== void 0 && \"value\" in descriptor ? failureSnapshot(descriptor.value) : void 0;\n\t} catch (_sdkPropertyTrap) {\n\t\treturn;\n\t}\n}\n/** Validate and detach an arbitrary serializable failure payload. */\nfunction failureSnapshot(value) {\n\tif (typeof value !== \"object\" || value === null) return void 0;\n\ttry {\n\t\tconst candidate = value;\n\t\tconst message = candidate.message;\n\t\tconst code = candidate.code;\n\t\tconst status = candidate.status;\n\t\tconst providerRetryAfterMs = candidate.providerRetryAfterMs;\n\t\tconst requestId = candidate.requestId;\n\t\tif (typeof message !== \"string\" || message.length === 0 || typeof code !== \"string\" || code.length === 0 || status !== void 0 && (!Number.isInteger(status) || status < 100 || status > 599) || providerRetryAfterMs !== void 0 && (!Number.isFinite(providerRetryAfterMs) || providerRetryAfterMs <= 0) || requestId !== void 0 && (typeof requestId !== \"string\" || requestId.length === 0)) return void 0;\n\t\treturn Object.freeze({\n\t\t\tmessage,\n\t\t\tcode,\n\t\t\t...status === void 0 ? {} : { status },\n\t\t\t...providerRetryAfterMs === void 0 ? {} : { providerRetryAfterMs },\n\t\t\t...requestId === void 0 ? {} : { requestId }\n\t\t});\n\t} catch (_sdkFailureGetter) {\n\t\treturn;\n\t}\n}\n/** Read an SDK error message without letting an accessor replace the primary failure. */\nfunction errorMessage(error) {\n\ttry {\n\t\tconst message = error.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t} catch (_sdkMessageGetter) {}\n\treturn \"LLM adapter failed\";\n}\n/** Trust only Harness-owned codes; third-party SDK codes are not our taxonomy. */\nfunction harnessErrorCode(error) {\n\treturn error instanceof HarnessError ? error.code : \"UNKNOWN\";\n}\n//#endregion\n//#region lib/types/api-key.js\n/**\n* The one definition of a well-formed provider API key, shared by every\n* adapter that puts one in an HTTP header.\n* @module @deepseek-ai/dsh-llm/api-key\n*/\n/**\n* Characters an HTTP header value carries verbatim and every known provider\n* key uses: printable ASCII, space excluded. A key outside this set cannot\n* reach any provider — `fetch` refuses to build the header — so this is a\n* transport invariant rather than one provider's policy. Latin-1 is excluded\n* deliberately: a header could carry it, but no provider issues it, and\n* admitting it trades a local explained refusal for an opaque 401.\n*/\nconst LEGAL_API_KEY = /^[\\x21-\\x7E]+$/;\n/**\n* Judge one *supplied* API key, trimming surrounding whitespace first.\n*\n* Trimming is silent because a padded key has one unambiguous reading; every\n* other defect is reported. Absence is a configuration state this function\n* never sees — a profile naming no credential authenticates through the\n* provider's own ambient discovery or OAuth — so callers decide whether a\n* value was supplied before asking.\n* @param raw - the key exactly as configured, stored, or typed.\n* @returns the trimmed key, or why it cannot be used.\n*/\nfunction normalizeApiKey(raw) {\n\tconst value = raw.trim();\n\tif (value.length === 0) return {\n\t\tok: false,\n\t\treason: \"empty\"\n\t};\n\tif (!LEGAL_API_KEY.test(value)) return {\n\t\tok: false,\n\t\treason: \"illegalCharacters\"\n\t};\n\treturn {\n\t\tok: true,\n\t\tvalue\n\t};\n}\n//#endregion\n//#region lib/types/attribution.js\n/**\n* Centralize the non-secret product identity every provider request sends as `User-Agent`, keeping\n* adapters from drifting. See\n* `.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md`.\n*\n* App-attribution vocabulary for provider requests.\n* @module @deepseek-ai/dsh-llm/attribution\n*/\nconst { version } = createRequire(import.meta.url)(\"../package.json\");\n/**\n* The harness's own identity: the default every adapter sends. Deployments\n* that need a white-label identity pass their own {@link AppIdentity} to\n* {@link attributionHeaders} — omission falls back to this default; nothing\n* can suppress attribution entirely.\n*/\nconst APP_IDENTITY = {\n\tproduct: \"deepseek-harness\",\n\tversion,\n\turl: \"https://github.com/deepseek-ai/deepseek-harness\"\n};\n/**\n* The standard `User-Agent` value: `product/version (+url)`. The\n* parenthesized `+url` comment is the conventional self-identification form\n* (RFC 9110 §10.1.5 product + comment syntax).\n* @param identity - the identity to render; defaults to {@link APP_IDENTITY}.\n* @returns the ready-to-send header value.\n*/\nfunction userAgent(identity = APP_IDENTITY) {\n\treturn `${identity.product}/${identity.version} (+${identity.url})`;\n}\n/**\n* Build the attribution headers an adapter must send on every provider\n* request. Header names are lowercase (HTTP field names are case-insensitive\n* on the wire).\n* @param identity - the identity to send; defaults to {@link APP_IDENTITY} — omission cannot suppress attribution.\n* @returns headers to merge into the provider request (currently just `user-agent`).\n*/\nfunction attributionHeaders(identity = APP_IDENTITY) {\n\treturn { \"user-agent\": userAgent(identity) };\n}\n//#endregion\n//#region lib/types/never.js\n/**\n* Exhaustiveness helper for closed core unions. Use {@link assertNever} at the default branch so a\n* new variant fails compilation at every required handler. Do not use it for declaration-merged\n* unions such as session events or content blocks: handle known variants and explicitly fall\n* through because plugins may add valid unknown cases.\n* @module @deepseek-ai/dsh-llm/never\n*/\n/**\n* Mark an unreachable closed-union branch. A newly unhandled typed variant fails at the call site;\n* a value that escaped its type throws with diagnostics at runtime.\n* @param value - the impossible value; typed `never` so an unhandled variant fails compilation at the call site.\n* @param context - optional label (e.g. the switch site) prefixed into the throw message.\n* @returns never — it always throws, with the offending value JSON-rendered in the message.\n*/\nfunction assertNever(value, context) {\n\tconst rendered = JSON.stringify(value) ?? String(value);\n\tthrow new Error(`unreachable variant${context ? ` in ${context}` : \"\"}: ${rendered}`);\n}\n//#endregion\n//#region lib/types/content.js\n/** Content-block structure helpers. @module @deepseek-ai/dsh-llm/content */\n/**\n* True when typed model content contains an image block, walking nested\n* tool-result content. This is the one recursive image walk shared by every\n* image policy (capability gating, text-only serialization, compaction\n* survey), so a consumer cannot silently diverge on nesting depth.\n* @param content - typed model content blocks.\n* @returns whether any nested block is an image.\n*/\nfunction contentHasImage(content) {\n\treturn content.some((block) => block.type === \"image\" || block.type === \"tool-result\" && contentHasImage(block.content));\n}\n//#endregion\n//#region lib/types/assembler.js\n/**\n* Incremental chunk-to-message assembler. This is the single canonical assembly\n* algorithm used by the agent loop to build an assistant message from a chunk\n* stream while logging the raw chunks for replay fidelity.\n*\n* @module @deepseek-ai/dsh-llm/assembler\n*/\n/**\n* Incrementally assembles raw {@link StreamChunk}s into complete\n* {@link ContentBlock}s and a final assistant {@link Message}.\n*\n* The agent loop feeds it while logging raw chunks for replay fidelity, then\n* reads `blocks()` / `message()` / `usage` / `finish` once the stream ends.\n*\n* Tolerant of delta-only protocols (no block-start/end); deltas arriving for\n* an index already closed by `block-end` are ignored (malformed stream) so a\n* misbehaving adapter cannot grow memory or corrupt a completed block.\n*/\nvar BlockAssembler = class {\n\tpartials = /* @__PURE__ */ new Map();\n\torder = [];\n\t_usage;\n\t_finish;\n\t_replayState = void 0;\n\t/**\n\t* Feed one chunk into the assembly state.\n\t* @param chunk - the next raw chunk, in stream order.\n\t*/\n\tpush(chunk) {\n\t\tswitch (chunk.type) {\n\t\t\tcase \"block-start\":\n\t\t\t\tif (!this.partials.has(chunk.index)) {\n\t\t\t\t\tthis.order.push(chunk.index);\n\t\t\t\t\tthis.partials.set(chunk.index, {\n\t\t\t\t\t\tblockType: chunk.blockType,\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\ttoolCallArguments: \"\"\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\tcase \"text-delta\":\n\t\t\tcase \"reasoning-delta\": {\n\t\t\t\tconst partial = this.ensure(chunk.index, chunk.type === \"text-delta\" ? \"text\" : \"reasoning\");\n\t\t\t\tif (partial.block) return;\n\t\t\t\tpartial.text += chunk.text;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"tool-call-delta\": {\n\t\t\t\tconst partial = this.ensure(chunk.index, \"tool-call\");\n\t\t\t\tif (partial.block) return;\n\t\t\t\tpartial.toolCallId = chunk.id;\n\t\t\t\tif (chunk.name) partial.toolCallName = chunk.name;\n\t\t\t\tpartial.toolCallArguments += chunk.argumentsDelta;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"block-end\": {\n\t\t\t\tconst partial = this.ensure(chunk.index, chunk.block.type);\n\t\t\t\tif (partial.block) return;\n\t\t\t\tpartial.block = chunk.block;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"usage\":\n\t\t\t\tthis._usage = chunk.usage;\n\t\t\t\treturn;\n\t\t\tcase \"finish\":\n\t\t\t\tthis._finish = chunk.reason;\n\t\t\t\tthis._replayState = chunk.replayState;\n\t\t\t\treturn;\n\t\t\tdefault: return assertNever(chunk, \"BlockAssembler.push\");\n\t\t}\n\t}\n\tensure(index, blockType) {\n\t\tlet partial = this.partials.get(index);\n\t\tif (!partial) {\n\t\t\tpartial = {\n\t\t\t\tblockType,\n\t\t\t\ttext: \"\",\n\t\t\t\ttoolCallArguments: \"\"\n\t\t\t};\n\t\t\tthis.partials.set(index, partial);\n\t\t\tthis.order.push(index);\n\t\t}\n\t\treturn partial;\n\t}\n\tassemble(partial, index) {\n\t\tif (partial.block) return partial.block;\n\t\tswitch (partial.blockType) {\n\t\t\tcase \"text\": return {\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: partial.text\n\t\t\t};\n\t\t\tcase \"reasoning\": return {\n\t\t\t\ttype: \"reasoning\",\n\t\t\t\ttext: partial.text\n\t\t\t};\n\t\t\tcase \"tool-call\": return {\n\t\t\t\ttype: \"tool-call\",\n\t\t\t\tid: partial.toolCallId ?? CallId(`call-${index}`),\n\t\t\t\tname: partial.toolCallName ?? \"\",\n\t\t\t\targuments: partial.toolCallArguments\n\t\t\t};\n\t\t\tdefault: throw new Error(`cannot assemble incomplete block of type \"${partial.blockType}\"`);\n\t\t}\n\t}\n\t/** Invariant accessor: every index in `order` has a partial. */\n\tmustGet(index) {\n\t\tconst partial = this.partials.get(index);\n\t\tif (!partial) throw new Error(`BlockAssembler invariant violated: no partial for index ${index}`);\n\t\treturn partial;\n\t}\n\t/**\n\t* Assemble all blocks seen so far, in stream order.\n\t* @returns one block per seen index, except that max-token truncation drops\n\t* tool calls that cannot be executed safely; an open block assembles from\n\t* its accumulated deltas (an unknown block type never closed by `block-end` throws).\n\t*/\n\tblocks() {\n\t\tconst blocks = this.order.map((index) => this.assemble(this.mustGet(index), index));\n\t\treturn this.finish.kind === \"max-tokens\" ? blocks.filter((block) => block.type !== \"tool-call\") : blocks;\n\t}\n\t/** Usage from the `usage` chunk; undefined until one arrives. */\n\tget usage() {\n\t\treturn this._usage;\n\t}\n\t/** Finish reason from the `finish` chunk; `{kind: 'stop'}` when the stream ended without one. */\n\tget finish() {\n\t\treturn this._finish ?? { kind: \"stop\" };\n\t}\n\t/** Adapter-private replay state from the terminal finish chunk, if any. */\n\tget replayState() {\n\t\treturn this._replayState;\n\t}\n\t/**\n\t* The assembled assistant message.\n\t* @param source - producer attribution for the assembled message.\n\t* @returns a frozen assistant-role message over `blocks()` (same open-block assembly rules).\n\t*/\n\tmessage(source = {\n\t\tkind: \"plugin\",\n\t\tplugin: \"dsh-llm/assembler\"\n\t}) {\n\t\treturn createMessage({\n\t\t\trole: \"assistant\",\n\t\t\tcontent: this.blocks(),\n\t\t\tsource\n\t\t});\n\t}\n};\n//#endregion\n//#region lib/types/index.js\n/**\n* LLM service: adapter registry with a waterfall-interceptable streaming call\n* API. Exports the `LlmRuntime` default, the abstract `LlmAdapter` for\n* provider backends, and `BlockAssembler` for chunk assembly.\n*\n* @module @deepseek-ai/dsh-llm\n*/\n/**\n* Typed error for LLM-related failures. Extends {@link HarnessError}, so the\n* `code` string (e.g. `AUTH`, `RATE_LIMIT`, `NO_ADAPTER`) is shared taxonomy.\n*/\nvar LlmError = class extends HarnessError {\n\t/** Serializable facts retained beside this live Error. */\n\tfailure;\n\t/**\n\t* @param message - non-empty human-readable failure summary.\n\t* @param code - non-empty stable provider-neutral machine code.\n\t* @param options - optional cause and validated serializable provider facts.\n\t*/\n\tconstructor(message, code, options) {\n\t\tif (typeof message !== \"string\" || message.length === 0) throw new Error(\"LlmError message must be a non-empty string\");\n\t\tif (typeof code !== \"string\" || code.length === 0) throw new Error(\"LlmError code must be a non-empty string\");\n\t\tif (options?.status !== void 0 && (!Number.isInteger(options.status) || options.status < 100 || options.status > 599)) throw new Error(\"LlmError status must be an integer from 100 through 599\");\n\t\tif (options?.providerRetryAfterMs !== void 0 && (!Number.isFinite(options.providerRetryAfterMs) || options.providerRetryAfterMs <= 0)) throw new Error(\"LlmError providerRetryAfterMs must be a positive finite number\");\n\t\tif (options?.requestId !== void 0 && (typeof options.requestId !== \"string\" || options.requestId.length === 0)) throw new Error(\"LlmError requestId must be a non-empty string\");\n\t\tsuper(message, code, options);\n\t\tthis.name = \"LlmError\";\n\t\tthis.failure = Object.freeze({\n\t\t\tmessage,\n\t\t\tcode,\n\t\t\t...options?.status === void 0 ? {} : { status: options.status },\n\t\t\t...options?.providerRetryAfterMs === void 0 ? {} : { providerRetryAfterMs: options.providerRetryAfterMs },\n\t\t\t...options?.requestId === void 0 ? {} : { requestId: options.requestId }\n\t\t});\n\t}\n};\n/**\n* Accept one supplied credential, or refuse it as unusable.\n*\n* A stored key arrives from the credentials seam, a `.env` line, or a shell\n* export, all of which pick up surrounding whitespace, so trimming is silent.\n* Anything else fails here rather than inside `fetch`, whose ByteString\n* refusal names a UTF-16 code point instead of the setting to change. The key\n* never enters the message: `ref` names where to fix it, and echoing any part\n* of a secret into a log or a UI is the failure this diagnosis avoids.\n*\n* Lives beside {@link LlmError} rather than in `./api-key.ts` so the predicate\n* module stays dependency-free; both adapters share this one diagnosis instead\n* of keeping near-identical local copies.\n* @param raw - the credential exactly as supplied.\n* @param pkg - the refusing package name, prefixed to the diagnostic.\n* @param ref - the credential reference the value resolved through.\n* @returns the trimmed, usable key.\n*/\nfunction assertUsableApiKey(raw, pkg, ref) {\n\tconst checked = normalizeApiKey(raw);\n\tif (checked.ok) return checked.value;\n\tthrow new LlmError(checked.reason === \"empty\" ? `${pkg}: the API key resolved from ${ref} is blank; set ${ref} to the raw key (the web Models page writes it) or export it in the launching environment` : `${pkg}: the API key resolved from ${ref} contains characters no HTTP header can carry; set ${ref} to the raw key alone (the web Models page writes it)`, INVALID_CREDENTIAL_CODE);\n}\n/**\n* Provider-wire adapter for the harness message and stream vocabulary. Register implementations\n* with `ctx.llm.registerAdapter(providers, adapter)`. Every provider HTTP request must include\n* `attributionHeaders()`; prove the headers are added in the wire request or library header hook. The direct-fetch\n* DeepSeek and library-backed pi-ai adapters meet this contract through different internals.\n*/\nvar LlmAdapter = class {\n\t/**\n\t* Describe one provider route owned by this adapter.\n\t* @param provider - a route passed to `registerAdapter()` for this instance.\n\t* @returns detached display metadata whose id must equal `provider`.\n\t*/\n\tproviderInfo(provider) {\n\t\treturn {\n\t\t\tid: provider,\n\t\t\tname: provider\n\t\t};\n\t}\n\t/**\n\t* Return the provider-owned retry policy captured with this route.\n\t* @param _provider - a route passed to `registerAdapter()` for this instance.\n\t* @returns a resolved policy, or `undefined` to use the normal defaults.\n\t*/\n\tproviderRetryPolicy(_provider) {}\n\t/**\n\t* List models this adapter can currently advertise for one owned provider.\n\t* The result is advisory: an adapter may accept unlisted model ids, and\n\t* consumers must not turn absence into request rejection.\n\t* @param _provider - one provider route owned by this adapter.\n\t* @returns discoverable models in adapter-preferred order.\n\t*/\n\tlistModels(_provider) {\n\t\treturn Promise.resolve([]);\n\t}\n\t/**\n\t* Resolve all metadata available for one exact model. This query is\n\t* independent of the advisory catalog and does not validate request routing.\n\t* @param provider - one provider route owned by this adapter.\n\t* @param model - exact model id passed to {@link GenerateOptions.model}.\n\t* @param _signal - cancellation for this exact-model lookup; asynchronous\n\t* implementations must settle promptly after it aborts.\n\t* @returns provider/model identity plus any context, call-default, and reasoning metadata.\n\t*/\n\tresolveModel(provider, model, _signal) {\n\t\treturn Promise.resolve({\n\t\t\tprovider,\n\t\t\tid: model,\n\t\t\tname: model\n\t\t});\n\t}\n};\n/**\n* The abstract `llm` service: an adapter registry plus a streaming model-call\n* API, interceptable via the `llm/stream` waterfall.\n*/\nvar LlmRuntime = class extends Service {\n\tadapters = /* @__PURE__ */ new Map();\n\tdirectory = /* @__PURE__ */ new Map();\n\tdiscoveries = /* @__PURE__ */ new Map();\n\tconstructor(ctx) {\n\t\tsuper(ctx, \"llm\");\n\t}\n\t/** Notify topology observers without letting one broken listener veto the commit. */\n\temitAdaptersUpdated() {\n\t\tlet invariantFailure;\n\t\tfor (const listener of this.ctx.events.dispatch(\"emit\", [\"llm/adapters-updated\"])) try {\n\t\t\tconst returned = listener();\n\t\t\tif (returned != null && typeof returned.then === \"function\") Promise.resolve(returned).then(void 0, (error) => {\n\t\t\t\tthis.warnAdaptersListenerFailure(error);\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error?.code === \"INVARIANT\") {\n\t\t\t\tinvariantFailure ??= error;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.warnAdaptersListenerFailure(error);\n\t\t}\n\t\tif (invariantFailure !== void 0) throw invariantFailure;\n\t}\n\t/** Contained-listener diagnostic shared by the sync and async failure paths. */\n\twarnAdaptersListenerFailure(error) {\n\t\tthis.ctx.logger.warn(\"llm: an llm/adapters-updated listener failed\");\n\t\tthis.ctx.logger.warn(error);\n\t}\n\t/**\n\t* Register an adapter for the given provider routes. Throws `LlmError` with code\n\t* `DUPLICATE_ADAPTER` if any provider already has an adapter (all-or-nothing).\n\t* Disposed with the fiber.\n\t* @param providers - every provider route this adapter should serve.\n\t* @param adapter - the adapter that streams calls for those providers.\n\t* @returns the disposer, carrying {@link AdapterRegistrationHandle.replace}.\n\t*/\n\tregisterAdapter(providers, adapter) {\n\t\tconst owned = /* @__PURE__ */ new Set();\n\t\tlet released = false;\n\t\tconst dispose = this.ctx.effect(function* () {\n\t\t\tif (providers.length === 0) throw new LlmError(\"an adapter must register at least one provider\", \"INVALID_ADAPTER\");\n\t\t\tthis.commitRoutes(owned, this.prepareRoutes(providers, adapter, owned));\n\t\t\tyield () => {\n\t\t\t\treleased = true;\n\t\t\t\tfor (const provider of owned) this.adapters.delete(provider);\n\t\t\t\towned.clear();\n\t\t\t\tthis.emitAdaptersUpdated();\n\t\t\t};\n\t\t}.bind(this), \"llm.registerAdapter()\");\n\t\tconst handle = (() => void dispose());\n\t\thandle.replace = (next) => {\n\t\t\tif (released) throw new LlmError(\"a disposed adapter registration cannot replace its routes\", \"REGISTRATION_DISPOSED\");\n\t\t\tthis.commitRoutes(owned, this.prepareRoutes(next, adapter, owned));\n\t\t};\n\t\treturn handle;\n\t}\n\t/**\n\t* Validate one candidate route set for `adapter`, treating routes this\n\t* registration already holds as available. Nothing is mutated: a rejected\n\t* candidate leaves the registry exactly as it was.\n\t*/\n\tprepareRoutes(providers, adapter, owned) {\n\t\tconst unique = /* @__PURE__ */ new Set();\n\t\tconst registrations = [];\n\t\tfor (const provider of providers) {\n\t\t\tif (provider.length === 0) throw new LlmError(\"adapter provider names must be non-empty\", \"INVALID_ADAPTER\");\n\t\t\tif (unique.has(provider) || this.adapters.has(provider) && !owned.has(provider)) throw new LlmError(`an adapter for provider \"${provider}\" is already registered`, \"DUPLICATE_ADAPTER\");\n\t\t\tconst info = adapter.providerInfo(provider);\n\t\t\tif (typeof info.id !== \"string\" || info.id !== provider || typeof info.name !== \"string\" || info.name.length === 0) throw new LlmError(`adapter metadata for provider \"${provider}\" must preserve its id and have a non-empty name`, \"INVALID_ADAPTER\");\n\t\t\tunique.add(provider);\n\t\t\tconst retryPolicy = adapter.providerRetryPolicy(provider) ?? resolveRetryPolicy(void 0, `llm: provider \"${provider}\" retryPolicy`);\n\t\t\tregistrations.push({\n\t\t\t\tadapter,\n\t\t\t\tprovider: {\n\t\t\t\t\tid: info.id,\n\t\t\t\t\tname: info.name\n\t\t\t\t},\n\t\t\t\tretryPolicy\n\t\t\t});\n\t\t}\n\t\treturn registrations;\n\t}\n\t/**\n\t* Swap this registration's routes for the prepared ones in one synchronous\n\t* section, so no observer can see the registry between the release and the\n\t* re-registration. The route set's one mutation point is also where\n\t* `llm/adapters-updated` is published, so a `replace` announces itself\n\t* exactly like a first registration.\n\t*/\n\tcommitRoutes(owned, registrations) {\n\t\tfor (const provider of owned) this.adapters.delete(provider);\n\t\towned.clear();\n\t\tfor (const registration of registrations) {\n\t\t\tthis.adapters.set(registration.provider.id, registration);\n\t\t\towned.add(registration.provider.id);\n\t\t}\n\t\tthis.emitAdaptersUpdated();\n\t}\n\t/**\n\t* Describe provider routes with a registered adapter.\n\t* @returns detached provider metadata in registration order.\n\t*/\n\tlistProviders() {\n\t\treturn [...this.adapters.values()].map(({ provider }) => ({ ...provider }));\n\t}\n\t/**\n\t* Declare provider routes an adapter plugin can activate through\n\t* configuration. Registration is all-or-nothing: an empty list, invalid\n\t* entry, or a provider already declared by any registration throws\n\t* `LlmError` without registering the rest. Disposed with the fiber.\n\t* @param entries - every configurable provider this plugin owns.\n\t* @returns a handle that withdraws all of them, and can atomically replace them.\n\t*/\n\tregisterConfigurableProviders(entries) {\n\t\tlet held = [];\n\t\tlet disposed = false;\n\t\t/**\n\t\t* Validate a candidate set in full against everything this registration\n\t\t* does not already hold, then publish it. Nothing is written until the\n\t\t* whole set passes, so a refused candidate leaves the current entries in\n\t\t* place — the property that makes `replace` a swap rather than a\n\t\t* delete-then-add that can strand the directory empty.\n\t\t*/\n\t\tconst commit = (candidates) => {\n\t\t\tconst detached = [];\n\t\t\tconst own = new Set(held.map((entry) => entry.provider));\n\t\t\tfor (const entry of candidates) {\n\t\t\t\tif (entry.provider.length === 0 || entry.displayName.length === 0 || entry.settingsNs.length === 0) throw new LlmError(\"configurable providers need a non-empty provider, displayName, and settingsNs\", \"INVALID_DIRECTORY\");\n\t\t\t\tif (entry.settingsPath.some((segment) => segment.length === 0)) throw new LlmError(`configurable provider \"${entry.provider}\" has an empty settingsPath segment`, \"INVALID_DIRECTORY\");\n\t\t\t\tif (this.directory.has(entry.provider) && !own.has(entry.provider) || detached.some((seen) => seen.provider === entry.provider)) throw new LlmError(`configurable provider \"${entry.provider}\" is already declared`, \"DUPLICATE_DIRECTORY\");\n\t\t\t\tdetached.push({\n\t\t\t\t\t...entry,\n\t\t\t\t\tsettingsPath: [...entry.settingsPath]\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (const entry of held) this.directory.delete(entry.provider);\n\t\t\tfor (const entry of detached) this.directory.set(entry.provider, entry);\n\t\t\theld = detached;\n\t\t\tthis.emitAdaptersUpdated();\n\t\t};\n\t\tconst dispose = this.ctx.effect(function* () {\n\t\t\tif (entries.length === 0) throw new LlmError(\"a configurable-provider registration must declare at least one provider\", \"INVALID_DIRECTORY\");\n\t\t\tcommit(entries);\n\t\t\tyield () => {\n\t\t\t\tdisposed = true;\n\t\t\t\tfor (const entry of held) this.directory.delete(entry.provider);\n\t\t\t\theld = [];\n\t\t\t\tthis.emitAdaptersUpdated();\n\t\t\t};\n\t\t}.bind(this), \"llm.registerConfigurableProviders()\");\n\t\tconst handle = (() => void dispose());\n\t\thandle.replace = (next) => {\n\t\t\tif (disposed) throw new LlmError(\"this configurable-provider registration was disposed\", \"REGISTRATION_DISPOSED\");\n\t\t\tcommit(next);\n\t\t};\n\t\treturn handle;\n\t}\n\t/**\n\t* List every declared configurable provider, registered or dormant.\n\t* @returns detached directory entries in declaration order.\n\t*/\n\tlistConfigurableProviders() {\n\t\treturn [...this.directory.values()].map((entry) => ({\n\t\t\t...entry,\n\t\t\tsettingsPath: [...entry.settingsPath]\n\t\t}));\n\t}\n\t/**\n\t* Offer to interrogate provider endpoints on behalf of the settings\n\t* namespace this plugin owns. The namespace is the key because that is what\n\t* a configuration surface already holds from the configurable-provider\n\t* directory, and because a provider being *added* has no route to name yet.\n\t* Disposed with the fiber.\n\t* @param settingsNs - the namespace whose profiles this discovery serves.\n\t* @param discover - interrogates one endpoint; must honor `request.signal`.\n\t* @returns the disposer that withdraws the offer.\n\t*/\n\tregisterModelDiscovery(settingsNs, discover) {\n\t\tconst dispose = this.ctx.effect(function* () {\n\t\t\tif (settingsNs.length === 0) throw new LlmError(\"model discovery needs a non-empty settings namespace\", \"INVALID_DISCOVERY\");\n\t\t\tif (this.discoveries.has(settingsNs)) throw new LlmError(`model discovery for \"${settingsNs}\" is already registered`, \"DUPLICATE_DISCOVERY\");\n\t\t\tthis.discoveries.set(settingsNs, discover);\n\t\t\tyield () => {\n\t\t\t\tthis.discoveries.delete(settingsNs);\n\t\t\t};\n\t\t}.bind(this), \"llm.registerModelDiscovery()\");\n\t\treturn () => void dispose();\n\t}\n\t/**\n\t* Interrogate one provider endpoint for the models it advertises. The\n\t* request describes a draft, not a stored route, so nothing here reads or\n\t* writes settings or credentials — the caller owns both, and the reply is\n\t* candidate metadata a surface may offer for adoption.\n\t* @param settingsNs - namespace whose registered discovery serves this draft.\n\t* @param request - the endpoint, protocol, and one-shot credential to use.\n\t* @returns the advertised models, deduplicated in endpoint order.\n\t*/\n\tasync discoverModels(settingsNs, request) {\n\t\tconst discover = this.discoveries.get(settingsNs);\n\t\tif (discover === void 0) throw new LlmError(`no model discovery is registered for \"${settingsNs}\"`, \"NO_DISCOVERY\");\n\t\tif ((request.provider ?? \"\").length === 0 && (request.baseURL ?? \"\").length === 0) throw new LlmError(\"model discovery needs a provider route or a baseURL\", \"INVALID_DISCOVERY\");\n\t\tconst discovered = await discover(request);\n\t\tconst seen = /* @__PURE__ */ new Set();\n\t\tconst models = [];\n\t\tfor (const model of discovered) {\n\t\t\tif (typeof model.id !== \"string\" || model.id.length === 0 || seen.has(model.id)) continue;\n\t\t\tseen.add(model.id);\n\t\t\tmodels.push({\n\t\t\t\tid: model.id,\n\t\t\t\t...model.name === void 0 ? {} : { name: model.name },\n\t\t\t\t...model.contextWindow === void 0 ? {} : { contextWindow: model.contextWindow },\n\t\t\t\t...model.maxTokens === void 0 ? {} : { maxTokens: model.maxTokens }\n\t\t\t});\n\t\t}\n\t\treturn models;\n\t}\n\t/**\n\t* Resolve the retry policy captured when one provider route was registered.\n\t* @param provider - registered provider route to inspect.\n\t* @returns the provider-owned policy, with normal defaults already resolved.\n\t*/\n\tproviderRetryPolicy(provider) {\n\t\treturn this.registration(provider).retryPolicy;\n\t}\n\t/** Detach typed adapter-owned modality metadata. */\n\tdetachedModalities(modalities) {\n\t\treturn modalities === void 0 ? void 0 : [...modalities];\n\t}\n\t/**\n\t* Discover models advertised by one registered provider. Catalog membership\n\t* is advisory and never changes routing or request validation.\n\t* @param provider - registered provider route to inspect.\n\t* @returns detached model metadata in adapter-preferred order.\n\t*/\n\tasync listModels(provider) {\n\t\tconst models = await this.registration(provider).adapter.listModels(provider);\n\t\tconst seen = /* @__PURE__ */ new Set();\n\t\treturn models.map((model) => {\n\t\t\tif (typeof model.provider !== \"string\" || model.provider !== provider || typeof model.id !== \"string\" || model.id.length === 0 || typeof model.name !== \"string\" || model.name.length === 0 || model.description !== void 0 && typeof model.description !== \"string\" || seen.has(model.id)) throw new LlmError(`adapter returned invalid or duplicate model metadata for provider \"${provider}\"`, \"INVALID_CATALOG\");\n\t\t\tseen.add(model.id);\n\t\t\tconst inputModalities = this.detachedModalities(model.inputModalities);\n\t\t\treturn {\n\t\t\t\tprovider: model.provider,\n\t\t\t\tid: model.id,\n\t\t\t\tname: model.name,\n\t\t\t\t...model.description === void 0 ? {} : { description: model.description },\n\t\t\t\t...inputModalities === void 0 ? {} : { inputModalities }\n\t\t\t};\n\t\t});\n\t}\n\t/**\n\t* Resolve and validate all metadata from the adapter that owns one exact\n\t* route. The result is detached from adapter-owned objects; catalog\n\t* membership remains advisory and does not control request routing.\n\t* @param provider - registered provider route to inspect.\n\t* @param model - exact model id passed to the adapter.\n\t* @param signal - optional cancellation for adapter-owned asynchronous lookup.\n\t* @returns exact model identity plus available context and reasoning metadata.\n\t*/\n\tasync resolveModelInfo(provider, model, signal) {\n\t\treturn this.resolveModelInfoFor(this.registration(provider), model, signal);\n\t}\n\tasync resolveModelInfoFor(registration, model, signal) {\n\t\tconst provider = registration.provider.id;\n\t\tconst resolved = await registration.adapter.resolveModel(provider, model, signal);\n\t\tif (typeof resolved.provider !== \"string\" || resolved.provider !== provider || typeof resolved.id !== \"string\" || resolved.id !== model || typeof resolved.name !== \"string\" || resolved.name.length === 0 || resolved.description !== void 0 && typeof resolved.description !== \"string\") throw new LlmError(`adapter returned invalid exact model metadata for provider \"${provider}\" model \"${model}\"`, \"INVALID_MODEL_INFO\");\n\t\tconst context = resolved.context;\n\t\tif (context !== void 0 && (!Number.isInteger(context.contextWindow) || context.contextWindow <= 0)) throw new LlmError(`adapter returned invalid context metadata for provider \"${provider}\" model \"${model}\"`, \"INVALID_MODEL_CONTEXT\");\n\t\tconst inputModalities = this.detachedModalities(resolved.inputModalities);\n\t\tconst defaultMaxTokens = resolved.defaultMaxTokens;\n\t\tif (defaultMaxTokens !== void 0 && (!Number.isSafeInteger(defaultMaxTokens) || defaultMaxTokens <= 0)) throw new LlmError(`adapter returned invalid default maxTokens for provider \"${provider}\" model \"${model}\"`, \"INVALID_MODEL_MAX_TOKENS\");\n\t\tconst info = {\n\t\t\tprovider,\n\t\t\tid: model,\n\t\t\tname: resolved.name,\n\t\t\t...resolved.description === void 0 ? {} : { description: resolved.description },\n\t\t\t...inputModalities === void 0 ? {} : { inputModalities },\n\t\t\t...context === void 0 ? {} : { context: { contextWindow: context.contextWindow } },\n\t\t\t...defaultMaxTokens === void 0 ? {} : { defaultMaxTokens }\n\t\t};\n\t\tconst reasoning = resolved.reasoning;\n\t\tif (reasoning === void 0) return info;\n\t\tif (reasoning.efforts.length === 0) throw new LlmError(`adapter returned invalid reasoning metadata for provider \"${provider}\" model \"${model}\"`, \"INVALID_MODEL_REASONING\");\n\t\tconst seen = /* @__PURE__ */ new Set();\n\t\tconst efforts = reasoning.efforts.map((effort) => {\n\t\t\tif (typeof effort.id !== \"string\" || effort.id.length === 0 || typeof effort.name !== \"string\" || effort.name.length === 0 || effort.description !== void 0 && typeof effort.description !== \"string\" || seen.has(effort.id)) throw new LlmError(`adapter returned invalid or duplicate reasoning effort metadata for provider \"${provider}\" model \"${model}\"`, \"INVALID_MODEL_REASONING\");\n\t\t\tseen.add(effort.id);\n\t\t\treturn {\n\t\t\t\tid: effort.id,\n\t\t\t\tname: effort.name,\n\t\t\t\t...effort.description === void 0 ? {} : { description: effort.description }\n\t\t\t};\n\t\t});\n\t\tif (reasoning.defaultEffort !== void 0 && !seen.has(reasoning.defaultEffort)) throw new LlmError(`adapter returned an unknown default reasoning effort for provider \"${provider}\" model \"${model}\"`, \"INVALID_MODEL_REASONING\");\n\t\treturn {\n\t\t\t...info,\n\t\t\treasoning: {\n\t\t\t\tefforts,\n\t\t\t\t...reasoning.defaultEffort === void 0 ? {} : { defaultEffort: reasoning.defaultEffort }\n\t\t\t}\n\t\t};\n\t}\n\t/**\n\t* Validate a conversation call config against its exact model capability and\n\t* materialize adapter-configured defaults. Unsupported explicit efforts\n\t* reject before provider I/O; no clamping or aliasing is performed. This\n\t* standalone query does not bind a later dispatch; use {@link prepareCall}\n\t* when logging and streaming must share one adapter registration.\n\t* @param config - provider/model route and optional request controls.\n\t* @param signal - optional cancellation for adapter-owned capability lookup.\n\t* @returns a detached config only when a default must be materialized.\n\t*/\n\tasync resolveCallConfig(config, signal) {\n\t\treturn (await this.resolveCallFor(this.registration(config.provider), config, signal)).config;\n\t}\n\tasync resolveCallFor(registration, config, signal) {\n\t\tconst info = await this.resolveModelInfoFor(registration, config.model, signal);\n\t\tconst defaulted = config.maxTokens === void 0 && info.defaultMaxTokens !== void 0 ? {\n\t\t\t...config,\n\t\t\tmaxTokens: info.defaultMaxTokens\n\t\t} : config;\n\t\tconst reasoning = info.reasoning;\n\t\tconst requested = defaulted.reasoningEffort;\n\t\tlet resolvedConfig = defaulted;\n\t\tif (reasoning === void 0) {\n\t\t\tif (requested !== void 0) throw new LlmError(`provider \"${config.provider}\" model \"${config.model}\" does not support reasoning effort \"${requested}\"`, \"UNSUPPORTED_REASONING_EFFORT\");\n\t\t} else {\n\t\t\tconst effective = requested ?? reasoning.defaultEffort;\n\t\t\tif (effective !== void 0) {\n\t\t\t\tif (!reasoning.efforts.some((effort) => effort.id === effective)) throw new LlmError(`provider \"${config.provider}\" model \"${config.model}\" does not support reasoning effort \"${effective}\"`, \"UNSUPPORTED_REASONING_EFFORT\");\n\t\t\t\tif (requested !== effective) resolvedConfig = {\n\t\t\t\t\t...defaulted,\n\t\t\t\t\treasoningEffort: effective\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tconfig: resolvedConfig,\n\t\t\t...info.context === void 0 ? {} : { context: info.context }\n\t\t};\n\t}\n\t/**\n\t* Resolve one call under its current adapter registration. The returned\n\t* one-shot handle keeps that registration across header logging and dispatch,\n\t* so HMR cannot combine one adapter's capability result with another adapter.\n\t* @param config - provider/model route and optional request controls.\n\t* @param signal - optional cancellation for adapter-owned capability lookup.\n\t* @returns a prepared config and its registration-bound stream entry point.\n\t*/\n\tasync prepareCall(config, signal) {\n\t\tconst registration = this.registration(config.provider);\n\t\tconst resolved = await this.resolveCallFor(registration, config, signal);\n\t\tconst resolvedConfig = deepFreeze(structuredClone(resolved.config));\n\t\tconst context = resolved.context === void 0 ? void 0 : deepFreeze(structuredClone(resolved.context));\n\t\tconst adapterDefaults = deepFreeze({\n\t\t\t...config.reasoningEffort === void 0 && resolvedConfig.reasoningEffort !== void 0 ? { reasoningEffort: true } : {},\n\t\t\t...config.maxTokens === void 0 && resolvedConfig.maxTokens !== void 0 ? { maxTokens: true } : {}\n\t\t});\n\t\tlet dispatched = false;\n\t\treturn Object.freeze({\n\t\t\tconfig: resolvedConfig,\n\t\t\tretryPolicy: registration.retryPolicy,\n\t\t\tadapterDefaults,\n\t\t\t...context === void 0 ? {} : { context },\n\t\t\tstream: (options) => {\n\t\t\t\tif (dispatched) throw new LlmError(\"a prepared LLM call can only be dispatched once\", \"INVALID_PREPARED_CALL\");\n\t\t\t\tif (!callConfigEquals(options, resolvedConfig)) throw new LlmError(\"prepared LLM call config changed before adapter dispatch\", \"INVALID_PREPARED_CALL\");\n\t\t\t\tdispatched = true;\n\t\t\t\treturn this.streamWithRegistration(options, {\n\t\t\t\t\tregistration,\n\t\t\t\t\tconfig: resolvedConfig\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\tregistration(provider) {\n\t\tconst registration = this.adapters.get(provider);\n\t\tif (!registration) throw new LlmError(`no adapter registered for provider \"${provider}\"`, \"NO_ADAPTER\");\n\t\treturn registration;\n\t}\n\t/** Remove replay state whose historical route is owned by another adapter. */\n\tforAdapter(options, adapter) {\n\t\tconst messages = options.messages.map((message) => {\n\t\t\tconst source = message.source;\n\t\t\tif (message.role !== \"assistant\" || source.kind !== \"model\" || source.replayState === void 0) return message;\n\t\t\tif (this.adapters.get(source.provider)?.adapter === adapter) return message;\n\t\t\treturn freezeMessage({\n\t\t\t\t...message,\n\t\t\t\tsource: {\n\t\t\t\t\tkind: \"model\",\n\t\t\t\t\tprovider: source.provider,\n\t\t\t\t\tmodel: source.model\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\tif (messages.every((message, index) => message === options.messages[index])) return options;\n\t\tconst filtered = {\n\t\t\t...options,\n\t\t\tmessages\n\t\t};\n\t\treturn Object.isFrozen(options) ? deepFreeze(filtered) : filtered;\n\t}\n\t/**\n\t* Final adapter boundary. Adapter selection, dispatch, iterator construction,\n\t* and iteration failures become one terminal failure chunk. Middleware and\n\t* downstream consumer failures remain thrown plugin or consumer errors.\n\t*/\n\tasync *adapterStream(options, prepared) {\n\t\tlet iterator;\n\t\ttry {\n\t\t\tconst registration = prepared?.registration ?? this.registration(options.provider);\n\t\t\tconst resolvedConfig = prepared === void 0 ? (await this.resolveCallFor(registration, options, options.signal)).config : prepared.config;\n\t\t\tif (prepared !== void 0 && !callConfigEquals(options, resolvedConfig)) throw new LlmError(\"prepared LLM call config changed before adapter dispatch\", \"INVALID_PREPARED_CALL\");\n\t\t\tconst resolvedOptions = callConfigEquals(options, resolvedConfig) ? options : Object.isFrozen(options) ? deepFreeze({\n\t\t\t\t...options,\n\t\t\t\t...resolvedConfig\n\t\t\t}) : {\n\t\t\t\t...options,\n\t\t\t\t...resolvedConfig\n\t\t\t};\n\t\t\tconst adapter = registration.adapter;\n\t\t\titerator = adapter.stream(this.forAdapter(resolvedOptions, adapter))[Symbol.asyncIterator]();\n\t\t} catch (error) {\n\t\t\tyield adapterFailureChunk(error, options.signal);\n\t\t\treturn;\n\t\t}\n\t\tlet completed = false;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tlet item;\n\t\t\t\ttry {\n\t\t\t\t\tconst next = await iterator.next();\n\t\t\t\t\titem = next.done ? { done: true } : {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue: next.value\n\t\t\t\t\t};\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcompleted = true;\n\t\t\t\t\tyield adapterFailureChunk(error, options.signal);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (item.done) {\n\t\t\t\t\tcompleted = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tyield item.value;\n\t\t\t}\n\t\t} finally {\n\t\t\tif (!completed) {\n\t\t\t\tconst close = iterator.return?.bind(iterator);\n\t\t\t\tif (close) await close();\n\t\t\t}\n\t\t}\n\t}\n\t/**\n\t* Stream one model call as raw chunks (token-level deltas). Replay state is\n\t* retained only when the same adapter instance owns its historical provider\n\t* and the target provider. Final adapter selection remains fixed through\n\t* asynchronous exact-model resolution and dispatch. Adapter selection,\n\t* dispatch, and iteration failures become terminal `error` or `aborted`\n\t* finish chunks; middleware, nested-call, cleanup, and consumer failures\n\t* remain thrown.\n\t* @param options - the full request; `options.provider` selects the adapter.\n\t* @returns the chunk stream, possibly wrapped by `llm/stream` listeners.\n\t*/\n\tstream(options) {\n\t\treturn this.streamWithRegistration(options);\n\t}\n\tstreamWithRegistration(options, prepared) {\n\t\treturn this.ctx.waterfall(this, \"llm/stream\", options, () => this.adapterStream(options, prepared));\n\t}\n};\n/** Convert one adapter throw into the stream protocol's terminal outcome. */\nfunction adapterFailureChunk(error, signal) {\n\tconst failure = normalizeLlmFailure(error);\n\treturn {\n\t\ttype: \"finish\",\n\t\treason: signal?.aborted || failure.code === \"ABORTED\" ? {\n\t\t\tkind: \"aborted\",\n\t\t\tfailure\n\t\t} : {\n\t\t\tkind: \"error\",\n\t\t\tfailure\n\t\t}\n\t};\n}\n//#endregion\nexport { APP_IDENTITY, BlockAssembler, CONTEXT_SUMMARY_MAX_CHARS, CONTEXT_WINDOW_EXCEEDED_CODE, CallId, EMPTY_RESPONSE_CODE, HarnessError, INVALID_CREDENTIAL_CODE, LlmAdapter, LlmError, LlmRuntime, LlmRuntime as default, MessageId, ProviderRequestId, QUOTA_EXCEEDED_CODE, ReasoningEffortId, RetryPolicySchema, assertNever, assertUsableApiKey, attributionHeaders, boundContextSummary, callConfigEquals, contentHasImage, createAssistantMessage, createMessage, createToolResultMessage, createUserMessage, deepFreeze, errorChain, freezeMessage, isAgentLoopRequest, isContextWindowExceededError, isHarnessError, isQuotaExceededError, isTokenDelta, markAgentLoopRequest, normalizeApiKey, resolveRetryPolicy, userAgent };\n","import { Service } from \"@deepseek-ai/cordis\";\nimport { isAbsolute } from \"node:path\";\nimport { CallId, MessageId, assertNever, callConfigEquals, deepFreeze, freezeMessage } from \"@deepseek-ai/dsh-llm\";\nimport { scopeOf, scopeTarget } from \"@deepseek-ai/dsh-scope\";\n//#region lib/types/types.js\n/**\n* Brand a string as a {@link SessionId}.\n* @param id - the raw session id string.\n* @returns the same string, branded (a compile-time cast — no runtime cost).\n*/\nfunction SessionId(id) {\n\treturn id;\n}\n/**\n* The on-disk session format version, stamped into every newly-written {@link SessionHeader}\n* and enforced by every persistence backend on load. The single source of truth for the\n* version — write sites and the load-time check all read it.\n* While the harness is unreleased it is pinned at `0`: no compatibility is\n* implied, incompatible logs are rejected, and no migration is provided.\n*\n* The version is a single monotonic integer with no major/minor split. Whether\n* a bump is needed is decided by what the WRITER emits, never by what a newer\n* reader can accept: bump exactly when an older runtime could no longer handle\n* a new log with full semantic correctness (\"parses without error\" is not\n* correctness — silently skipping content that shapes reconstruction is a\n* wrong read). Only structural changes reach that bar: the header shape, the\n* {@link SessionEvent} envelope, core event semantics, or the surface\n* mechanism (the {@link SurfaceEventType} set and {@link SurfaceOp} variants).\n* Adding an ordinary event type does not bump — the per-event\n* {@link SessionEvent.ignorable} guard covers vocabulary growth instead. When\n* in doubt, bump: a near-identity upgrade step is almost free, a missed bump\n* makes older runtimes read new logs wrong silently. The full mechanism\n* (upgrade-step chain, in-memory view conversion, migrate-on-continue) is\n* recorded in the session-log-version-mechanism Agent Note\n* (`.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md`).\n*/\nconst SESSION_FORMAT_VERSION = 0;\n//#endregion\n//#region lib/types/json.js\n/** Lossless-JSON validation and detached snapshots for durable session data. @module @deepseek-ai/dsh-session/json */\n/** Whether a realm-owned intrinsic prototype is backed by its native constructor. */\nfunction hasIntrinsicConstructor(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, \"Object\");\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */\nfunction hasPlainArrayPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);\n}\n/** Whether an object is a plain or null-prototype record from any JavaScript realm. */\nfunction hasPlainObjectPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype(prototype);\n}\n/** Return every JSON-visible object key, or reject own data JSON would discard. */\nfunction enumerableStringKeys(value) {\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.some((key) => typeof key !== \"string\" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;\n\treturn keys;\n}\n/** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */\nfunction walkJsonValue(value, detach) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tlet root;\n\tconst assign = (destination, item) => {\n\t\tif (destination === void 0) return;\n\t\tif (destination.kind === \"root\") root = item;\n\t\telse if (destination.kind === \"array\") destination.target[destination.index] = item;\n\t\telse Object.defineProperty(destination.target, destination.key, {\n\t\t\tvalue: item,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t});\n\t};\n\tconst tasks = [{\n\t\tkind: \"visit\",\n\t\tvalue,\n\t\t...detach ? { destination: { kind: \"root\" } } : {}\n\t}];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (task.kind === \"leave\") {\n\t\t\tancestors.delete(task.source);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"array-item\") {\n\t\t\tif (!Object.prototype.hasOwnProperty.call(task.source, task.index)) return void 0;\n\t\t\ttasks.push({\n\t\t\t\tkind: \"visit\",\n\t\t\t\tvalue: task.source[task.index],\n\t\t\t\t...task.target === void 0 ? {} : { destination: {\n\t\t\t\t\tkind: \"array\",\n\t\t\t\t\ttarget: task.target,\n\t\t\t\t\tindex: task.index\n\t\t\t\t} }\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"object-property\") {\n\t\t\ttasks.push({\n\t\t\t\tkind: \"visit\",\n\t\t\t\tvalue: task.source[task.key],\n\t\t\t\t...task.target === void 0 ? {} : { destination: {\n\t\t\t\t\tkind: \"object\",\n\t\t\t\t\ttarget: task.target,\n\t\t\t\t\tkey: task.key\n\t\t\t\t} }\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst current = task.value;\n\t\tif (current === null) {\n\t\t\tassign(task.destination, null);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof current === \"boolean\" || typeof current === \"string\") {\n\t\t\tassign(task.destination, current);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof current === \"number\") {\n\t\t\tif (!Number.isFinite(current) || Object.is(current, -0)) return void 0;\n\t\t\tassign(task.destination, current);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof current !== \"object\") return void 0;\n\t\tif (ancestors.has(current)) return void 0;\n\t\tif (Array.isArray(current)) {\n\t\t\tif (!hasPlainArrayPrototype(current)) return void 0;\n\t\t\tconst length = current.length;\n\t\t\tif (Reflect.ownKeys(current).length !== length + 1) return void 0;\n\t\t\tconst target = detach ? [] : void 0;\n\t\t\tif (target !== void 0) assign(task.destination, target);\n\t\t\tancestors.add(current);\n\t\t\ttasks.push({\n\t\t\t\tkind: \"leave\",\n\t\t\t\tsource: current\n\t\t\t});\n\t\t\tfor (let index = length - 1; index >= 0; index--) tasks.push({\n\t\t\t\tkind: \"array-item\",\n\t\t\t\tsource: current,\n\t\t\t\tindex,\n\t\t\t\t...target === void 0 ? {} : { target }\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasPlainObjectPrototype(current)) return void 0;\n\t\tconst keys = enumerableStringKeys(current);\n\t\tif (keys === void 0) return void 0;\n\t\tconst target = detach ? {} : void 0;\n\t\tif (target !== void 0) assign(task.destination, target);\n\t\tancestors.add(current);\n\t\ttasks.push({\n\t\t\tkind: \"leave\",\n\t\t\tsource: current\n\t\t});\n\t\tfor (let index = keys.length - 1; index >= 0; index--) {\n\t\t\tconst key = keys[index];\n\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\tif (key === void 0) return void 0;\n\t\t\ttasks.push({\n\t\t\t\tkind: \"object-property\",\n\t\t\t\tsource: current,\n\t\t\t\tkey,\n\t\t\t\t...target === void 0 ? {} : { target }\n\t\t\t});\n\t\t}\n\t}\n\treturn detach ? root : true;\n}\n/**\n* Validate and detach lossless JSON in one read per property, so a stateful\n* getter cannot change between validation and copying. Traversal is iterative,\n* so valid nesting is bounded by available memory rather than the JavaScript\n* call stack. Accepts ordinary arrays, plain or null-prototype objects, and JSON\n* scalars; rejects sparse, cyclic, exotic, negative-zero, and non-finite values.\n* Getter throws propagate.\n*\n* @param value - the candidate value to validate and detach.\n* @returns the detached snapshot, or `undefined` when the value is not\n* losslessly JSON-serializable.\n*/\nfunction snapshotJsonValue(value) {\n\treturn walkJsonValue(value, true);\n}\n/**\n* Test the same lossless JSON boundary as {@link snapshotJsonValue} without\n* detaching it. Only own enumerable string properties participate; `toJSON`\n* is ignored and getters run, so persistence boundaries use the snapshotter.\n* @param value - the candidate event data to test.\n* @returns whether `value` survives JSON round-trip losslessly.\n*/\nfunction isJsonValue(value) {\n\treturn walkJsonValue(value, false) === true;\n}\n//#endregion\n//#region lib/types/surface.js\n/**\n* Surface layer on top of the session event log: an ordered view of events\n* that produce LLM messages. The append-only log remains the source of truth.\n*\n* Browser-safe: web clients consume this subpath export, so it must stay free\n* of `node:` imports (they break the vite bundle).\n*\n* @module @deepseek-ai/dsh-session/surface\n*/\n/** Runtime counterpart of the message-producing event union. */\nconst SURFACE_EVENT_TYPES = new Set([\n\t\"user/message\",\n\t\"assistant/message\",\n\t\"tool/result\"\n]);\n/**\n* Whether an event type can join the model-visible surface.\n* @param type - event type to test.\n* @returns true for one of the three message-producing event types.\n*/\nfunction isSurfaceEligibleType(type) {\n\treturn SURFACE_EVENT_TYPES.has(type);\n}\n/**\n* Narrow an event to a surface-eligible event carrying its required marker.\n* @param event - event to test.\n* @returns true when both the type and marker identify a surface event.\n*/\nfunction isSurfaceEvent(event) {\n\tif (!SURFACE_EVENT_TYPES.has(event.type)) return false;\n\treturn event.surfaceOp !== void 0;\n}\n/**\n* Narrow an event to an append-origin surface event: one that entered the\n* surface at its own log position and was never itself a replacement copy.\n*\n* The model-visible surface deliberately shadows replaced ranges, so it is the\n* wrong source for a human transcript — a landed replacement would erase\n* conversation the user already saw. Append-origin events are that transcript's\n* durable source material; replacement copies stay model-only.\n* @param event - event to test.\n* @returns true when the event appended to the surface tail.\n*/\nfunction isAppendSurfaceEvent(event) {\n\treturn isSurfaceEvent(event) && event.surfaceOp === \"append\";\n}\n/**\n* Narrow an event to a surface replacement: a node that shadowed an existing\n* surface range instead of appending to the tail. The counterpart of\n* {@link isAppendSurfaceEvent} over the two {@link SurfaceOp} variants.\n* @param event - event to test.\n* @returns true when the event replaced a surface range.\n*/\nfunction isReplacementSurfaceEvent(event) {\n\treturn isSurfaceEvent(event) && event.surfaceOp !== \"append\";\n}\n/**\n* Project a single event into the LLM message it derives to, or null when it\n* produces none — a non-surface event (chunk, boundary, log-only record) or an\n* empty-content assistant/message (which exists only to host usage). This is\n* THE per-node projection rule: `Session.deriveMessages` folds it over the\n* live surface, external reconstructors and pure projections fold the same\n* function over a log prefix's surface to rebuild the exact messages any\n* request was built from. The returned message is the already frozen message\n* nested in the event wrapper and shared by delivery, durable history, and\n* model requests.\n* @param event - the event to project.\n* @returns the derived message, or null when the event produces none.\n*/\nfunction deriveEventMessage(event) {\n\tswitch (event.type) {\n\t\tcase \"user/message\": return event.data;\n\t\tcase \"assistant/message\":\n\t\t\tif (event.data.message.content.length === 0) return null;\n\t\t\treturn event.data.message;\n\t\tcase \"tool/result\": return event.data.message;\n\t\tdefault: return null;\n\t}\n}\n/** Create an empty surface fold state. */\nfunction createFoldState() {\n\treturn {\n\t\tnodes: [],\n\t\treplaceGeneration: 0\n\t};\n}\n/** Whether a runtime value is a non-negative safe event sequence. */\nfunction isEventSeq(value) {\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n/** Whether a runtime value is the exact positional-replacement shape. */\nfunction isReplaceOp(value) {\n\tconst op = value;\n\treturn Object.keys(op).length === 3 && Object.hasOwn(op, \"op\") && Object.hasOwn(op, \"start\") && Object.hasOwn(op, \"end\") && op[\"op\"] === \"replace\" && isEventSeq(op[\"start\"]) && isEventSeq(op[\"end\"]);\n}\n/** Validate event-local surface eligibility and return its operation. */\nfunction surfaceOpOf(event) {\n\tconst raw = event;\n\tif (!isSurfaceEligibleType(event.type)) {\n\t\tif (raw.surfaceOp !== void 0) throw new Error(`session event \"${event.type}\" is not surface-eligible and cannot carry surfaceOp`);\n\t\tif (raw.sourceEventSeqs !== void 0) throw new Error(`session event \"${event.type}\" is not surface-eligible and cannot carry sourceEventSeqs`);\n\t\treturn;\n\t}\n\tconst op = raw.surfaceOp;\n\tif (op === void 0) throw new Error(`session event \"${event.type}\" is surface-eligible and requires a surfaceOp marker`);\n\tif (op === \"append\") return op;\n\tif (op === null || typeof op !== \"object\" || Array.isArray(op)) throw new Error(`session event \"${event.type}\" carries an invalid surfaceOp`);\n\tif (!isReplaceOp(op)) throw new Error(`session event \"${event.type}\" carries an invalid replace surfaceOp`);\n\treturn op;\n}\n/** Validate cited source-event seqs against prior log entries and the replacement range. */\nfunction assertProvenance(event, shadowedSeqs) {\n\tconst raw = event.sourceEventSeqs;\n\tconst sources = /* @__PURE__ */ new Set();\n\tif (raw !== void 0) {\n\t\tif (!Array.isArray(raw)) throw new Error(`sourceEventSeqs on event at seq ${event.seq} must be an array when present`);\n\t\tif (raw.length === 0 && event.type !== \"assistant/message\") throw new Error(\"sourceEventSeqs must not be empty except on assistant/message\");\n\t\tlet nonEarlierSource;\n\t\tfor (const source of raw) {\n\t\t\tif (!isEventSeq(source)) throw new Error(`session event \"${event.type}\" sourceEventSeqs must densely contain non-negative safe integers`);\n\t\t\tsources.add(source);\n\t\t\tif (nonEarlierSource === void 0 && source >= event.seq) nonEarlierSource = source;\n\t\t}\n\t\tif (sources.size !== raw.length) throw new Error(\"sourceEventSeqs must not contain duplicates\");\n\t\tif (nonEarlierSource !== void 0) throw new Error(`sourceEventSeqs must reference earlier events: ${nonEarlierSource} >= current seq ${event.seq}`);\n\t}\n\tconst missing = shadowedSeqs.filter((seq) => !sources.has(seq));\n\tif (missing.length > 0) throw new Error(`surface replace: sourceEventSeqs must include every shadowed surface node; missing ${missing.join(\", \")}`);\n}\n/** Locate one replacement range without mutating the current fold state. */\nfunction replacementRange(state, op) {\n\tconst startIdx = state.nodes.indexOf(op.start);\n\tif (startIdx === -1) throw new Error(`surface replace: start seq ${op.start} not found in surface`);\n\tconst endIdx = state.nodes.indexOf(op.end);\n\tif (endIdx === -1) throw new Error(`surface replace: end seq ${op.end} not found in surface`);\n\tif (startIdx > endIdx) throw new Error(`surface replace: start seq ${op.start} (index ${startIdx}) is after end seq ${op.end} (index ${endIdx})`);\n\treturn {\n\t\tstartIdx,\n\t\tendIdx,\n\t\tshadowedSeqs: state.nodes.slice(startIdx, endIdx + 1)\n\t};\n}\n/**\n* Deep structural equality over the session-event JSON value domain\n* (null/boolean/number/string, arrays, plain objects). Replaces\n* `node:util`'s isDeepStrictEqual to keep this module browser-safe.\n*/\nfunction isDeepEqualJson(a, b) {\n\tif (a === b) return true;\n\tif (Array.isArray(a) || Array.isArray(b)) {\n\t\tif (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n\t\treturn a.every((item, i) => isDeepEqualJson(item, b[i]));\n\t}\n\tif (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n\tconst aKeys = Object.keys(a);\n\tconst bRecord = b;\n\tif (aKeys.length !== Object.keys(b).length) return false;\n\treturn aKeys.every((key) => Object.hasOwn(b, key) && isDeepEqualJson(a[key], bRecord[key]));\n}\n/** Restrict a tool-result replacement to one current result's content. */\nfunction assertToolResultRewrite(event, shadowedSeqs, events, baseSeq) {\n\tif (event.type !== \"tool/result\") return;\n\tif (shadowedSeqs.length !== 1) throw new Error(\"tool/result surface replacement must rewrite exactly one current node\");\n\tfor (const originalSeq of shadowedSeqs) {\n\t\tconst original = events[originalSeq - baseSeq];\n\t\tif (original?.type !== \"tool/result\") throw new Error(\"tool/result surface replacement must target a current tool/result\");\n\t\tconst originalRest = { ...original.data };\n\t\tconst replacementRest = { ...event.data };\n\t\tconst originalResult = original.data.message.content[0];\n\t\tconst replacementResult = event.data.message.content[0];\n\t\toriginalRest[\"message\"] = {\n\t\t\t...original.data.message,\n\t\t\tcontent: [{\n\t\t\t\t...originalResult,\n\t\t\t\tcontent: null\n\t\t\t}]\n\t\t};\n\t\treplacementRest[\"message\"] = {\n\t\t\t...event.data.message,\n\t\t\tcontent: [{\n\t\t\t\t...replacementResult,\n\t\t\t\tcontent: null\n\t\t\t}]\n\t\t};\n\t\tif (!isDeepEqualJson(originalRest, replacementRest)) throw new Error(\"tool/result surface replacement may change only content\");\n\t}\n}\n/** Validate one event at its replay boundary and prepare its atomic fold transition. */\nfunction planSurfaceEvent(state, event, expectedSeq, events, baseSeq) {\n\tif (event.seq !== expectedSeq) throw new Error(`session event seq ${event.seq} is not contiguous; expected ${expectedSeq}`);\n\tconst surfaceOp = surfaceOpOf(event);\n\tif (surfaceOp === void 0) return;\n\tif (surfaceOp === \"append\") {\n\t\tassertProvenance(event, []);\n\t\treturn {\n\t\t\tkind: \"append\",\n\t\t\tseq: event.seq\n\t\t};\n\t}\n\tconst range = replacementRange(state, surfaceOp);\n\tassertProvenance(event, range.shadowedSeqs);\n\tassertToolResultRewrite(event, range.shadowedSeqs, events, baseSeq);\n\treturn {\n\t\tkind: \"replace\",\n\t\tseq: event.seq,\n\t\tstart: surfaceOp.start,\n\t\tend: surfaceOp.end,\n\t\t...range\n\t};\n}\n/** Apply one event and return replacement metadata only when one occurred. */\nfunction applySurfaceEvent(state, event, expectedSeq, events, baseSeq) {\n\treturn applySurfacePlan(state, planSurfaceEvent(state, event, expectedSeq, events, baseSeq));\n}\n/** Commit one previously validated surface transition. */\nfunction applySurfacePlan(state, plan) {\n\tif (plan?.kind === \"append\") state.nodes.push(plan.seq);\n\telse if (plan?.kind === \"replace\") {\n\t\tstate.nodes.splice(plan.startIdx, plan.endIdx - plan.startIdx + 1, plan.seq);\n\t\tstate.replaceGeneration += 1;\n\t}\n\tif (plan?.kind !== \"replace\") return;\n\treturn {\n\t\tseq: plan.seq,\n\t\tstart: plan.start,\n\t\tend: plan.end,\n\t\tshadowedSeqs: plan.shadowedSeqs\n\t};\n}\n/**\n* Replay a complete session log through the canonical surface fold.\n* @param events - session events in contiguous seq order.\n* @returns detached current sequences and replacement history.\n* @throws when an event violates surface metadata, source-event references, range, or tool-result rewrite rules.\n*/\nfunction foldSurface(events) {\n\tconst state = createFoldState();\n\tconst replacements = [];\n\tfor (const [index, event] of events.entries()) {\n\t\tconst replacement = applySurfaceEvent(state, event, index, events, 0);\n\t\tif (replacement !== void 0) replacements.push(replacement);\n\t}\n\treturn {\n\t\tnodes: [...state.nodes],\n\t\treplacements\n\t};\n}\n/** Incremental ordered surface view and append-boundary validator. */\nvar SurfaceManager = class {\n\tlog;\n\tbaseSeq;\n\t/** Shared transition state; replacement history is not retained. */\n\t_state = createFoldState();\n\t/** Last processed absolute seq. */\n\t_lastProcessedSeq;\n\t/** Candidate already validated by `validateNext`, pending exact log admission. */\n\t_pendingPlan;\n\t/**\n\t* @param log - Contiguous complete log or loaded event window.\n\t* @param baseSeq - Absolute sequence of the window's first event.\n\t*/\n\tconstructor(log, baseSeq = 0) {\n\t\tthis.log = log;\n\t\tthis.baseSeq = baseSeq;\n\t\tthis._lastProcessedSeq = baseSeq - 1;\n\t}\n\t/**\n\t* Validate the next candidate without mutating the committed surface.\n\t* @param event - candidate event that has not entered the log yet.\n\t*/\n\tvalidateNext(event) {\n\t\tif (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta();\n\t\tconst expectedSeq = this.baseSeq + this.log.length;\n\t\tthis._pendingPlan = {\n\t\t\tevent,\n\t\t\texpectedSeq,\n\t\t\tplan: planSurfaceEvent(this._state, event, expectedSeq, this.log, this.baseSeq)\n\t\t};\n\t}\n\t/** Monotonic count of folded positional replacements. */\n\tget replaceGeneration() {\n\t\tif (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta();\n\t\treturn this._state.replaceGeneration;\n\t}\n\t/** Surface event sequences in model-visible order. */\n\tget nodes() {\n\t\tif (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta();\n\t\treturn this._state.nodes;\n\t}\n\t/** Fold events appended since the previous access. */\n\t_processDelta() {\n\t\tconst tailSeq = this.baseSeq + this.log.length - 1;\n\t\tfor (let seq = this._lastProcessedSeq + 1; seq <= tailSeq; seq++) {\n\t\t\tconst index = seq - this.baseSeq;\n\t\t\tconst event = this.log[index];\n\t\t\tconst pending = this._pendingPlan;\n\t\t\tif (pending?.event === event && pending.expectedSeq === seq) applySurfacePlan(this._state, pending.plan);\n\t\t\telse applySurfaceEvent(this._state, event, seq, this.log, this.baseSeq);\n\t\t\tif (pending !== void 0 && pending.expectedSeq <= seq) this._pendingPlan = void 0;\n\t\t\tthis._lastProcessedSeq = seq;\n\t\t}\n\t}\n};\n//#endregion\n//#region lib/types/request-header.js\n/**\n* Request-header reconstruction utilities over full `request/header` session\n* events. Anyone holding a session log reconstructs the {@link EpochHeader}\n* any request was built under by taking the latest canonical snapshot; the\n* loop uses the same equality helper to avoid logging unchanged headers.\n*\n* @module dsh-session/request-header\n*/\n/**\n* Normalize a header to canonical form: an empty system prompt and empty tool\n* list become absent fields, matching how requests are built. Logging, folding,\n* and comparison use this one representation.\n* @param header - the header to normalize (not mutated).\n* @returns the canonical header.\n*/\nfunction canonicalHeader(header) {\n\tconst adapterDefaults = header.adapterDefaults;\n\treturn {\n\t\tconfig: header.config,\n\t\t...adapterDefaults?.reasoningEffort === true || adapterDefaults?.maxTokens === true ? { adapterDefaults } : {},\n\t\t...header.system !== void 0 && header.system.length > 0 ? { system: header.system } : {},\n\t\t...header.tools !== void 0 && header.tools.length > 0 ? { tools: header.tools } : {}\n\t};\n}\n/** Canonical JSON equality for tool schemas assembled through the same path. */\nfunction sameSchema(a, b) {\n\treturn JSON.stringify(a) === JSON.stringify(b);\n}\n/**\n* Field-wise equality over canonical headers. Tool schemas compare in order.\n* @param a - one canonical header.\n* @param b - the other.\n* @returns whether config, system, and tools all match.\n*/\nfunction headerEquals(a, b) {\n\tif (!callConfigEquals(a.config, b.config) || a.adapterDefaults?.reasoningEffort !== b.adapterDefaults?.reasoningEffort || a.adapterDefaults?.maxTokens !== b.adapterDefaults?.maxTokens || a.system !== b.system) return false;\n\tconst at = a.tools ?? [];\n\tconst bt = b.tools ?? [];\n\treturn at.length === bt.length && at.every((tool, i) => sameSchema(tool, bt[i]));\n}\n/**\n* Fold the header events of a log (or any prefix) into the\n* {@link EpochHeader} in force after the last snapshot. Non-header events are\n* skipped. This is the pure offline reconstruction path; the live session\n* tracks the same fold incrementally.\n* @param events - session events in log order.\n* @param from - a previously folded state to continue from.\n* @returns the latest canonical header, or undefined when none exists yet.\n*/\nfunction foldRequestHeader(events, from) {\n\tlet state = from;\n\tfor (const event of events) if (event.type === \"request/header\") state = canonicalHeader(event.data.header);\n\treturn state;\n}\n//#endregion\n//#region lib/types/preparation.js\n/**\n* Ownership of one unpublished Session before registry publication.\n* @module @deepseek-ai/dsh-session/preparation\n*/\n/**\n* One exact unpublished Session and the provider state that keeps it usable.\n* Disposal is synchronous and idempotent. Providers decide whether release\n* returns the Session to a cache or discards it; publication may consume that\n* state before disposal, making the callback a no-op.\n*/\nvar SessionPreparation = class SessionPreparation {\n\toptions;\n\treleased = false;\n\t/** The exact Session to use for setup and publication. */\n\tsession;\n\tconstructor(session, options) {\n\t\tthis.options = options;\n\t\tthis.session = session;\n\t}\n\t/**\n\t* Wrap an unpublished Session in one preparation lifetime.\n\t* @param session - exact unpublished Session.\n\t* @param options - optional provider release behavior.\n\t* @returns a preparation disposed after publication or rollback.\n\t*/\n\tstatic create(session, options) {\n\t\treturn new SessionPreparation(session, options ?? {});\n\t}\n\t/** Release provider state once when this preparation leaves its caller. */\n\t[Symbol.dispose]() {\n\t\tif (this.released) return;\n\t\tthis.released = true;\n\t\tthis.options.release?.();\n\t}\n};\n//#endregion\n//#region lib/types/repair.js\n/**\n* Crash-recovery repair for an interrupted session log. It preserves a fully\n* written final turn and supplies the missing tool, step, and turn boundaries\n* needed to resume with a provider-valid transcript.\n* @module @deepseek-ai/dsh-session/repair\n*/\n/** Recovery code for an assistant tool request that never reached a recorded call start. */\nconst TOOL_NOT_STARTED = \"TOOL_NOT_STARTED\";\n/** Recovery code for a recorded tool call whose completed outcome was not durably recorded. */\nconst TOOL_OUTCOME_UNKNOWN = \"TOOL_OUTCOME_UNKNOWN\";\n/**\n* Return deterministic synthetic events that close an open tail turn. Unmatched\n* calls receive error results first, followed by an open `step/end` and an\n* interrupted `turn/end`; sequences continue the log and timestamps reuse the\n* last real event. A balanced or empty log returns no events.\n*\n* @param events - the loaded durable log to scan (a valid committed prefix, possibly with a crash tail).\n* @returns the synthetic closer events to append after `events`, in order; empty when the log is already balanced.\n*/\nfunction interruptedTurnClosers(events) {\n\tlet openTurn = null;\n\tlet openStep = null;\n\tconst pendingCalls = /* @__PURE__ */ new Map();\n\tfor (const event of events) switch (event.type) {\n\t\tcase \"turn/start\":\n\t\t\topenTurn = event.data.turn;\n\t\t\topenStep = null;\n\t\t\tpendingCalls.clear();\n\t\t\tbreak;\n\t\tcase \"turn/end\":\n\t\t\topenTurn = null;\n\t\t\topenStep = null;\n\t\t\tpendingCalls.clear();\n\t\t\tbreak;\n\t\tcase \"step/start\":\n\t\t\topenStep = event.data.step;\n\t\t\tbreak;\n\t\tcase \"step/end\":\n\t\t\tpendingCalls.clear();\n\t\t\topenStep = null;\n\t\t\tbreak;\n\t\tcase \"assistant/message\":\n\t\t\tfor (const block of event.data.message.content) if (block.type === \"tool-call\") pendingCalls.set(block.id, { step: event.data.step });\n\t\t\tbreak;\n\t\tcase \"tool/call\":\n\t\t\t{\n\t\t\t\tconst entry = pendingCalls.get(event.data.callId);\n\t\t\t\tif (entry) entry.callSeq = event.seq;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"tool/result\":\n\t\t\tpendingCalls.delete(event.data.message.source.callId);\n\t\t\tbreak;\n\t\tdefault: break;\n\t}\n\tconst last = events.at(-1);\n\tif (openTurn === null || last === void 0) return [];\n\tlet seq = last.seq + 1;\n\tconst time = last.time;\n\tconst closers = [];\n\tfor (const [callId, { step, callSeq }] of pendingCalls) {\n\t\tconst started = callSeq !== void 0;\n\t\tconst message = freezeMessage({\n\t\t\tid: MessageId(`interrupted-tool-result-${callId}-${seq}`),\n\t\t\trole: \"user\",\n\t\t\tsource: {\n\t\t\t\tkind: \"tool\",\n\t\t\t\tcallId\n\t\t\t},\n\t\t\tcontent: [{\n\t\t\t\ttype: \"tool-result\",\n\t\t\t\ttoolCallId: callId,\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: started ? \"The tool call was interrupted after it was recorded, but no result was durably recorded. Its outcome is unknown. Decide whether to retry from the tool semantics: retry only if the operation is read-only or idempotent; if it may have side effects, first verify external state or ask the user. Do not retry blindly.\" : \"The tool call was interrupted before the Harness recorded it as started. Retry it if it is still needed.\"\n\t\t\t\t}]\n\t\t\t}]\n\t\t});\n\t\tclosers.push({\n\t\t\ttype: \"tool/result\",\n\t\t\tseq: seq++,\n\t\t\ttime,\n\t\t\tdata: {\n\t\t\t\tturn: openTurn,\n\t\t\t\tstep,\n\t\t\t\tmessage,\n\t\t\t\terror: started ? {\n\t\t\t\t\tname: \"ToolOutcomeUnknownError\",\n\t\t\t\t\tcode: TOOL_OUTCOME_UNKNOWN\n\t\t\t\t} : {\n\t\t\t\t\tname: \"ToolNotStartedError\",\n\t\t\t\t\tcode: TOOL_NOT_STARTED\n\t\t\t\t}\n\t\t\t},\n\t\t\tsurfaceOp: \"append\",\n\t\t\t...started ? { sourceEventSeqs: [callSeq] } : {}\n\t\t});\n\t}\n\tif (openStep !== null) closers.push({\n\t\ttype: \"step/end\",\n\t\tseq: seq++,\n\t\ttime,\n\t\tdata: {\n\t\t\tturn: openTurn,\n\t\t\tstep: openStep\n\t\t}\n\t});\n\tclosers.push({\n\t\ttype: \"turn/end\",\n\t\tseq: seq++,\n\t\ttime,\n\t\tdata: {\n\t\t\tturn: openTurn,\n\t\t\treason: { kind: \"interrupted\" }\n\t\t}\n\t});\n\treturn closers;\n}\n//#endregion\n//#region lib/types/chunk-rows.js\n/**\n* Lossless storage packing for `assistant/chunk` delta runs. Providers stream\n* token-sized deltas, so a log stores hundreds of near-identical event lines\n* whose JSON envelopes dwarf their payloads (~56× measured on a real DeepSeek\n* session). This module packs each run of consecutive same-block delta chunks\n* into ONE storage row — `text-chunks`, `reasoning-chunks`, or\n* `tool-call-chunks` — and expands rows back to the exact original events.\n*\n* Storage rows are a durable-encoding vocabulary, NOT session events: they\n* never enter `Session.events`, have no `SessionEventMap` entry, and use bare\n* (slash-less) type tags so a reader cannot confuse them with the event\n* taxonomy (precedent: the JSONL header line's `session` tag). The encoder\n* whitelists exact shapes — anything it does not fully recognize is stored\n* verbatim, so unknown fields or future chunk variants lose compression, never\n* data. The decoder validates before expanding and fails loud on a malformed\n* row-tagged value instead of silently dropping a whole run.\n*\n* @module @deepseek-ai/dsh-session/chunk-rows\n*/\n/**\n* Minimum members before a run packs. Below it a row's envelope rivals the\n* event lines it replaces. A format constant, not a tunable: both layouts\n* decode identically, so changing it never invalidates stored logs.\n*/\nconst MIN_RUN = 3;\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null;\n}\n/** Exact-key check: `value` has every key in `keys` and nothing else. */\nfunction hasExactKeys(value, keys) {\n\treturn Object.keys(value).length === keys.length && keys.every((k) => Object.hasOwn(value, k));\n}\n/**\n* Classify an event for packing: its delta kind when the ENTIRE shape\n* (envelope, data, chunk — exact keys, primitive types, integer seq/time) is\n* whitelisted, else `undefined` (store verbatim). Inputs come from live typed\n* appends AND parsed fixture files, so the checks are structural, not\n* type-trusted. Integer times keep gap encoding exact: a fractional time would\n* reconstruct through float subtraction/addition, which need not round-trip.\n*/\nfunction classify(event) {\n\tif (event.type !== \"assistant/chunk\") return void 0;\n\tif (!hasExactKeys(event, [\n\t\t\"type\",\n\t\t\"seq\",\n\t\t\"time\",\n\t\t\"data\"\n\t])) return void 0;\n\tif (!Number.isSafeInteger(event.seq) || event.seq < 0 || !Number.isSafeInteger(event.time)) return void 0;\n\tconst data = event.data;\n\tif (!isRecord(data) || !hasExactKeys(data, [\n\t\t\"turn\",\n\t\t\"step\",\n\t\t\"chunk\"\n\t])) return void 0;\n\tif (typeof data.turn !== \"number\" || typeof data.step !== \"number\") return void 0;\n\tconst chunk = data.chunk;\n\tif (!isRecord(chunk) || typeof chunk.index !== \"number\") return void 0;\n\tswitch (chunk.type) {\n\t\tcase \"text-delta\":\n\t\tcase \"reasoning-delta\": return hasExactKeys(chunk, [\n\t\t\t\"type\",\n\t\t\t\"index\",\n\t\t\t\"text\"\n\t\t]) && typeof chunk.text === \"string\" ? chunk.type : void 0;\n\t\tcase \"tool-call-delta\": return (hasExactKeys(chunk, [\n\t\t\t\"type\",\n\t\t\t\"index\",\n\t\t\t\"id\",\n\t\t\t\"argumentsDelta\"\n\t\t]) || hasExactKeys(chunk, [\n\t\t\t\"type\",\n\t\t\t\"index\",\n\t\t\t\"id\",\n\t\t\t\"name\",\n\t\t\t\"argumentsDelta\"\n\t\t]) && typeof chunk.name === \"string\") && typeof chunk.id === \"string\" && typeof chunk.argumentsDelta === \"string\" ? chunk.type : void 0;\n\t\tdefault: return;\n\t}\n}\n/** The tool-call fields of a whitelisted delta chunk (only after {@link classify} returned `'tool-call-delta'`). */\nfunction toolCallOf(event) {\n\treturn event.data.chunk;\n}\n/** The block index of a whitelisted delta chunk (not every {@link StreamChunk} variant carries one). */\nfunction indexOf(event) {\n\treturn event.data.chunk.index;\n}\n/** Whether `next` extends a run ending in `prev` (same kind already checked by the caller). */\nfunction continues(prev, next, kind) {\n\tif (next.seq !== prev.seq + 1) return false;\n\tif (!Number.isSafeInteger(next.time - prev.time)) return false;\n\tif (next.data.turn !== prev.data.turn || next.data.step !== prev.data.step) return false;\n\tif (indexOf(next) !== indexOf(prev)) return false;\n\tif (kind !== \"tool-call-delta\") return true;\n\tconst a = toolCallOf(prev);\n\tconst b = toolCallOf(next);\n\treturn a.id === b.id && Object.hasOwn(a, \"name\") === Object.hasOwn(b, \"name\") && a.name === b.name;\n}\n/** Build the row for a completed run (`run.length >= MIN_RUN`, uniform per {@link continues}). */\nfunction buildRow(kind, run) {\n\tconst first = run[0];\n\tconst base = {\n\t\tturn: first.data.turn,\n\t\tstep: first.data.step,\n\t\tindex: indexOf(first),\n\t\tdt: run.slice(1).map((event, i) => event.time - run[i].time)\n\t};\n\tconst envelope = {\n\t\tseq0: first.seq,\n\t\ttime0: first.time\n\t};\n\tif (kind === \"tool-call-delta\") {\n\t\tconst call = toolCallOf(first);\n\t\treturn {\n\t\t\ttype: \"tool-call-chunks\",\n\t\t\t...envelope,\n\t\t\tdata: {\n\t\t\t\t...base,\n\t\t\t\tid: CallId(call.id),\n\t\t\t\t...Object.hasOwn(call, \"name\") ? { name: call.name } : {},\n\t\t\t\targs: run.map((event) => event.data.chunk.argumentsDelta)\n\t\t\t}\n\t\t};\n\t}\n\tconst data = {\n\t\t...base,\n\t\ttexts: run.map((event) => event.data.chunk.text)\n\t};\n\treturn kind === \"text-delta\" ? {\n\t\ttype: \"text-chunks\",\n\t\t...envelope,\n\t\tdata\n\t} : {\n\t\ttype: \"reasoning-chunks\",\n\t\t...envelope,\n\t\tdata\n\t};\n}\n/**\n* Pack an event batch for storage: each run of at least {@link MIN_RUN}\n* consecutive whitelisted same-kind, same-block delta chunk events becomes one\n* {@link ChunkRow}; every other event passes through verbatim, in order.\n* Pure and stateless — safe over any array, including a batch whose runs were\n* split by flush boundaries (the split runs simply pack per batch).\n*\n* @param events - the batch to encode, in log order.\n* @returns the storage records to write, one JSONL line each.\n*/\nfunction packChunkRuns(events) {\n\tconst out = [];\n\tlet kind;\n\tlet run = [];\n\tconst flush = () => {\n\t\tif (kind !== void 0 && run.length >= MIN_RUN) out.push(buildRow(kind, run));\n\t\telse out.push(...run);\n\t\tkind = void 0;\n\t\trun = [];\n\t};\n\tfor (const event of events) {\n\t\tconst k = classify(event);\n\t\tif (k === void 0) {\n\t\t\tflush();\n\t\t\tout.push(event);\n\t\t\tcontinue;\n\t\t}\n\t\tconst delta = event;\n\t\tconst last = run[run.length - 1];\n\t\tif (k === kind && last !== void 0 && continues(last, delta, k)) {\n\t\t\trun.push(delta);\n\t\t\tcontinue;\n\t\t}\n\t\tflush();\n\t\tkind = k;\n\t\trun = [delta];\n\t}\n\tflush();\n\treturn out;\n}\n/** Throw the uniform malformed-row diagnostic. */\nfunction malformed(tag, why) {\n\tthrow new Error(`malformed ${tag} storage row: ${why}`);\n}\n/** Validate the shared run-data fields and the payload/dt arity; returns the member payload. */\nfunction validateRunData(tag, data, payloadKey) {\n\tif (typeof data.turn !== \"number\" || typeof data.step !== \"number\" || typeof data.index !== \"number\") malformed(tag, \"turn/step/index must be numbers\");\n\tconst payload = data[payloadKey];\n\tif (!Array.isArray(payload) || payload.length === 0 || payload.some((entry) => typeof entry !== \"string\")) malformed(tag, `${payloadKey} must be a non-empty string array`);\n\tconst dt = data.dt;\n\tif (!Array.isArray(dt) || dt.some((gap) => !Number.isSafeInteger(gap))) malformed(tag, \"dt must be an array of safe integers\");\n\tif (dt.length !== payload.length - 1) malformed(tag, `dt length ${dt.length} does not match ${payload.length} members`);\n\treturn payload;\n}\n/** Validate a row-tagged parsed value's envelope and data, throwing on any malformation. */\nfunction validateRow(value, tag) {\n\tif (!hasExactKeys(value, [\n\t\t\"type\",\n\t\t\"seq0\",\n\t\t\"time0\",\n\t\t\"data\"\n\t])) malformed(tag, \"envelope must be exactly {type, seq0, time0, data}\");\n\tif (!Number.isSafeInteger(value.seq0) || value.seq0 < 0) malformed(tag, \"seq0 must be a non-negative safe integer\");\n\tif (!Number.isSafeInteger(value.time0)) malformed(tag, \"time0 must be a safe integer\");\n\tconst data = value.data;\n\tif (!isRecord(data)) malformed(tag, \"data must be an object\");\n\tlet payload;\n\tif (tag === \"tool-call-chunks\") {\n\t\tconst withName = hasExactKeys(data, [\n\t\t\t\"turn\",\n\t\t\t\"step\",\n\t\t\t\"index\",\n\t\t\t\"id\",\n\t\t\t\"name\",\n\t\t\t\"dt\",\n\t\t\t\"args\"\n\t\t]);\n\t\tif (!withName && !hasExactKeys(data, [\n\t\t\t\"turn\",\n\t\t\t\"step\",\n\t\t\t\"index\",\n\t\t\t\"id\",\n\t\t\t\"dt\",\n\t\t\t\"args\"\n\t\t])) malformed(tag, \"data must be exactly {turn, step, index, id, name?, dt, args}\");\n\t\tif (typeof data.id !== \"string\" || withName && typeof data.name !== \"string\") malformed(tag, \"id (and name when present) must be strings\");\n\t\tpayload = validateRunData(tag, data, \"args\");\n\t} else {\n\t\tif (!hasExactKeys(data, [\n\t\t\t\"turn\",\n\t\t\t\"step\",\n\t\t\t\"index\",\n\t\t\t\"dt\",\n\t\t\t\"texts\"\n\t\t])) malformed(tag, \"data must be exactly {turn, step, index, dt, texts}\");\n\t\tpayload = validateRunData(tag, data, \"texts\");\n\t}\n\tif (!Number.isSafeInteger(value.seq0 + payload.length - 1)) malformed(tag, \"member seqs must stay safe integers\");\n\tlet time = value.time0;\n\tfor (const gap of data.dt) {\n\t\ttime += gap;\n\t\tif (!Number.isSafeInteger(time)) malformed(tag, \"member times must stay safe integers\");\n\t}\n\treturn value;\n}\n/** Expand a validated row back into its exact original events, in order. */\nfunction expandRow(row) {\n\tconst members = row.type === \"tool-call-chunks\" ? row.data.args : row.data.texts;\n\tconst events = [];\n\tlet time = row.time0;\n\tfor (let k = 0; k < members.length; k++) {\n\t\tif (k > 0) time += row.data.dt[k - 1];\n\t\tlet chunk;\n\t\tswitch (row.type) {\n\t\t\tcase \"text-chunks\":\n\t\t\t\tchunk = {\n\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\tindex: row.data.index,\n\t\t\t\t\ttext: members[k]\n\t\t\t\t};\n\t\t\t\tbreak;\n\t\t\tcase \"reasoning-chunks\":\n\t\t\t\tchunk = {\n\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\tindex: row.data.index,\n\t\t\t\t\ttext: members[k]\n\t\t\t\t};\n\t\t\t\tbreak;\n\t\t\tcase \"tool-call-chunks\":\n\t\t\t\tchunk = {\n\t\t\t\t\ttype: \"tool-call-delta\",\n\t\t\t\t\tindex: row.data.index,\n\t\t\t\t\tid: row.data.id,\n\t\t\t\t\t...Object.hasOwn(row.data, \"name\") ? { name: row.data.name } : {},\n\t\t\t\t\targumentsDelta: members[k]\n\t\t\t\t};\n\t\t\t\tbreak;\n\t\t\t/* v8 ignore next 2 -- validateRow only returns the three row tags */\n\t\t\tdefault: return assertNever(row, \"chunk-rows expandRow\");\n\t\t}\n\t\tevents.push({\n\t\t\ttype: \"assistant/chunk\",\n\t\t\tseq: row.seq0 + k,\n\t\t\ttime,\n\t\t\tdata: {\n\t\t\t\tturn: row.data.turn,\n\t\t\t\tstep: row.data.step,\n\t\t\t\tchunk\n\t\t\t}\n\t\t});\n\t}\n\treturn events;\n}\n/**\n* Decode one parsed JSONL line value into the session event(s) it stores.\n* Chunk-row-tagged values validate and expand (a malformed row throws — it is\n* corrupt storage, and treating it as an event would silently drop a whole\n* run); every other value passes through as a single event, unvalidated.\n*\n* @param value - one line's `JSON.parse` result.\n* @returns the stored events, in log order.\n*/\nfunction decodeStorageRecord(value) {\n\tif (!isRecord(value)) return [value];\n\tconst tag = value.type;\n\tif (tag !== \"text-chunks\" && tag !== \"reasoning-chunks\" && tag !== \"tool-call-chunks\") return [value];\n\treturn expandRow(validateRow(value, tag));\n}\n//#endregion\n//#region lib/types/known-event-types.js\n/**\n* GENERATED by `scripts/gen-persistence-catalog.ts` — do not edit by hand; run\n* `pnpm run gen-persistence-catalog` to regenerate (verified fresh by\n* `pnpm run verify-persistence-catalog`, part of `doc-sync`).\n* @module @deepseek-ai/dsh-session/known-event-types\n*/\n/**\n* Every `SessionEventMap` member declared in this repository — the event\n* vocabulary this build understands. The persistence read path refuses to\n* interpret a log containing a type outside this set unless the event\n* carries the envelope's `ignorable` marker (see `SessionEvent.ignorable`\n* in `./types.ts`): such a log was likely written by a newer harness, and\n* silently skipping a required event would reconstruct a wrong session.\n* Downstream (out-of-repo) plugin events are outside this list by\n* construction; a registration surface for them is deferred until such a\n* consumer exists.\n*/\nconst KNOWN_SESSION_EVENT_TYPES = new Set([\n\t\"agent-preset/selected\",\n\t\"agent/inbox/spliced\",\n\t\"approval/asked\",\n\t\"approval/decided\",\n\t\"approval/policy\",\n\t\"assistant/chunk\",\n\t\"assistant/message\",\n\t\"command/done\",\n\t\"command/run\",\n\t\"compaction/end\",\n\t\"compaction/prune\",\n\t\"compaction/start\",\n\t\"compaction/summary\",\n\t\"feedback/record\",\n\t\"goal/change\",\n\t\"hook/invoked\",\n\t\"hook/result\",\n\t\"llm/retry\",\n\t\"llm/retry-started\",\n\t\"permission/preset\",\n\t\"plan/mode\",\n\t\"request/context\",\n\t\"request/header\",\n\t\"sandbox/mode\",\n\t\"schedule/change\",\n\t\"session/end-seed\",\n\t\"session/title\",\n\t\"session/title-llm-request\",\n\t\"step/end\",\n\t\"step/start\",\n\t\"subagent/descriptor\",\n\t\"todo/write\",\n\t\"tool-workflow/agent-end\",\n\t\"tool-workflow/agent-start\",\n\t\"tool-workflow/run-end\",\n\t\"tool-workflow/run-start\",\n\t\"tool/call\",\n\t\"tool/code-dispatch\",\n\t\"tool/code-dispatch-start\",\n\t\"tool/result\",\n\t\"turn/end\",\n\t\"turn/start\",\n\t\"user/message\",\n\t\"web/deepseek-search-llm-request\"\n]);\n//#endregion\n//#region lib/types/index.js\n/**\n* Event-sourced session service: append-only session log, in-memory store, and\n* the derived LLM message history. Persistence is a plugin concern (subscribe\n* to `session/event`, drain on `session/flush`).\n*\n* @module @deepseek-ai/dsh-session\n*/\n/** Validate and freeze one detached creation header in place. */\nfunction validateSessionHeader(id, input) {\n\tif (input === null || typeof input !== \"object\" || Array.isArray(input)) throw new Error(\"session header is not a plain JSON record\");\n\tconst record = input;\n\tif (record.version !== 0) throw new Error(`session header version must be 0, got ${String(record.version)}`);\n\tif (record.id !== id) throw new Error(`session header id \"${String(record.id)}\" does not match session id \"${id}\"`);\n\tif (typeof record.createdAt !== \"number\" || !Number.isSafeInteger(record.createdAt) || record.createdAt < 0) throw new Error(\"session header createdAt must be a non-negative safe integer\");\n\tif (record.cwd !== void 0) {\n\t\tif (typeof record.cwd !== \"string\") throw new Error(\"session header cwd must be a string\");\n\t\tif (!isAbsolute(record.cwd)) throw new Error(`session header cwd must be an absolute path, got \"${record.cwd}\"`);\n\t}\n\tif (record.parentSession !== void 0 && typeof record.parentSession !== \"string\") throw new Error(\"session header parentSession must be a string\");\n\tif (record.seedLength !== void 0 && (typeof record.seedLength !== \"number\" || !Number.isSafeInteger(record.seedLength) || record.seedLength < 0)) throw new Error(\"session header seedLength must be a non-negative safe integer\");\n\tif (record.origin !== void 0 && record.origin !== \"subagent\") throw new Error(\"session header origin must be \\\"subagent\\\"\");\n\tif (record.delegationDepth !== void 0 && (typeof record.delegationDepth !== \"number\" || !Number.isSafeInteger(record.delegationDepth) || record.delegationDepth < 0)) throw new Error(\"session header delegationDepth must be a non-negative safe integer\");\n\tif (record.agentPreset !== void 0 && typeof record.agentPreset !== \"string\") throw new Error(\"session header agentPreset must be a string\");\n\treturn deepFreeze(record);\n}\n/** Validate and freeze one exclusively owned persistence header in place. */\nfunction validateRestoredSessionHeader(id, input) {\n\tif (input !== null && typeof input === \"object\" && !Array.isArray(input)) {\n\t\tconst prototype = Reflect.getPrototypeOf(input);\n\t\tif (prototype !== Object.prototype && prototype !== null) throw new Error(\"session header is not a plain JSON record\");\n\t}\n\treturn validateSessionHeader(id, input);\n}\n/** Detach, validate, and freeze the creation metadata published by a session. */\nfunction snapshotSessionHeader(id, source) {\n\tconst snapshot = snapshotJsonValue(source === void 0 ? {\n\t\tversion: 0,\n\t\tid,\n\t\tcreatedAt: Date.now()\n\t} : source);\n\tif (snapshot === void 0) throw new Error(\"session header is not losslessly JSON-serializable\");\n\treturn validateSessionHeader(id, snapshot);\n}\n/**\n* Validate an exclusively owned event and deeply freeze its identified message\n* without copying the event. The caller transfers an object graph that no\n* producer retains and that shares no mutable children with another event.\n* Use {@link snapshotSessionEvent} when exclusive ownership is not guaranteed.\n* @param event - exclusively owned event imported across a trusted boundary.\n* @returns the same event object with a validated, deeply frozen message.\n*/\nfunction adoptSessionEvent(event) {\n\tassertMessageEventShape(event, `session event at seq ${event.seq}`);\n\tswitch (event.type) {\n\t\tcase \"user/message\":\n\t\t\tdeepFreeze(event.data);\n\t\t\tbreak;\n\t\tcase \"assistant/message\":\n\t\tcase \"tool/result\":\n\t\t\tdeepFreeze(event.data.message);\n\t\t\tbreak;\n\t\tdefault: break;\n\t}\n\treturn event;\n}\n/**\n* Detach one event while preserving deep immutability for its identified message.\n* @param event - event imported across a query or persistence boundary.\n* @returns a detached event snapshot with a validated, deeply frozen message.\n*/\nfunction snapshotSessionEvent(event) {\n\treturn adoptSessionEvent(structuredClone(event));\n}\n/** Deep-freeze one acyclic JSON tree without consuming the JavaScript call stack. */\nfunction freezeRestoredObject(value) {\n\tconst pending = [value];\n\twhile (pending.length > 0) {\n\t\tconst current = pending.pop();\n\t\tObject.freeze(current);\n\t\tfor (const key in current) {\n\t\t\tconst child = current[key];\n\t\t\tif (child !== null && typeof child === \"object\") pending.push(child);\n\t\t}\n\t}\n\treturn value;\n}\n/** Validate the fixed event envelope after one-pass JSON materialization. */\nfunction assertSessionEventEnvelope(value, index) {\n\tconst event = value;\n\tif (event[\"type\"] === \"request/header-delta\") throw new Error(`seed event at index ${index} uses unsupported legacy request/header-delta format`);\n\tfor (const key in event) switch (key) {\n\t\tcase \"type\":\n\t\tcase \"seq\":\n\t\tcase \"time\":\n\t\tcase \"data\":\n\t\tcase \"surfaceOp\":\n\t\tcase \"sourceEventSeqs\":\n\t\tcase \"ignorable\": break;\n\t\tdefault: throw new Error(`seed event at index ${index} has an invalid event envelope`);\n\t}\n\tconst type = event[\"type\"];\n\tconst seq = event[\"seq\"];\n\tconst time = event[\"time\"];\n\tif (typeof type !== \"string\" || typeof seq !== \"number\" || !Number.isSafeInteger(seq) || seq < 0 || typeof time !== \"number\" || !Number.isSafeInteger(time) || event[\"data\"] === void 0 || event[\"ignorable\"] !== void 0 && event[\"ignorable\"] !== true) throw new Error(`seed event at index ${index} has an invalid event envelope`);\n\tswitch (type) {\n\t\tcase \"request/header\":\n\t\tcase \"user/message\":\n\t\tcase \"assistant/message\":\n\t\tcase \"tool/result\":\n\t\t\tassertCurrentLlmShape(event, index);\n\t\t\tbreak;\n\t}\n}\n/** Reject obsolete request headers and malformed messages at the seed/load boundary. */\nfunction assertCurrentLlmShape(event, index) {\n\tconst data = event[\"data\"];\n\tconst record = typeof data === \"object\" && data !== null ? data : void 0;\n\tif (event[\"type\"] === \"request/header\") {\n\t\tconst header = record?.[\"header\"];\n\t\tconst headerRecord = typeof header === \"object\" && header !== null && !Array.isArray(header) ? header : void 0;\n\t\tconst config = headerRecord?.[\"config\"];\n\t\tif (!hasProviderModel(config)) throw new Error(`seed request/header at index ${index} lacks provider/model`);\n\t\tconst configRecord = config;\n\t\tconst reasoningEffort = configRecord[\"reasoningEffort\"];\n\t\tif (reasoningEffort !== void 0 && (typeof reasoningEffort !== \"string\" || reasoningEffort.length === 0)) throw new Error(`seed request/header at index ${index} has an invalid reasoningEffort`);\n\t\tassertAdapterDefaults(headerRecord?.[\"adapterDefaults\"], configRecord, index);\n\t}\n\tconst type = event[\"type\"];\n\tif (type !== \"user/message\" && type !== \"assistant/message\" && type !== \"tool/result\") return;\n\tassertMessageEventShape(event, `seed ${type} at index ${index}`);\n}\nconst allowedAdapterKeys = new Set([\"reasoningEffort\", \"maxTokens\"]);\n/** Validate adapter-default markers imported from a durable request header. */\nfunction assertAdapterDefaults(value, config, index) {\n\tif (value === void 0) return;\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) throw new Error(`seed request/header at index ${index} has invalid adapterDefaults`);\n\tconst defaults = value;\n\tif (Object.keys(defaults).some((key) => !allowedAdapterKeys.has(key)) || Object.values(defaults).some((marker) => marker !== true) || defaults[\"reasoningEffort\"] === true && config[\"reasoningEffort\"] === void 0 || defaults[\"maxTokens\"] === true && config[\"maxTokens\"] === void 0) throw new Error(`seed request/header at index ${index} has invalid adapterDefaults`);\n}\n/** Validate only the event-specific invariants needed to safely replay a message. */\nfunction assertMessageEventShape(event, subject) {\n\tconst type = event[\"type\"];\n\tif (type !== \"user/message\" && type !== \"assistant/message\" && type !== \"tool/result\") return;\n\tconst data = event[\"data\"];\n\tconst record = typeof data === \"object\" && data !== null ? data : void 0;\n\tconst message = type === \"user/message\" ? record : record?.[\"message\"];\n\tif (typeof message !== \"object\" || message === null || typeof message[\"id\"] !== \"string\" || message[\"id\"] === \"\") throw new Error(`${subject} lacks an identified message`);\n\tconst messageRecord = message;\n\tconst expectedRole = type === \"assistant/message\" ? \"assistant\" : \"user\";\n\tif (messageRecord[\"role\"] !== expectedRole) throw new Error(`${subject} message must have role \"${expectedRole}\"`);\n\tconst source = messageRecord[\"source\"];\n\tif (typeof source !== \"object\" || source === null || typeof source[\"kind\"] !== \"string\" || source[\"kind\"] === \"\") throw new Error(`${subject} message has invalid source`);\n\tif (!Array.isArray(messageRecord[\"content\"])) throw new Error(`${subject} message has invalid content`);\n\tconst sourceRecord = source;\n\tif (type === \"assistant/message\") {\n\t\tif (sourceRecord[\"kind\"] !== \"model\" || !hasProviderModel(sourceRecord)) throw new Error(`${subject} message must have model source`);\n\t\treturn;\n\t}\n\tif (type !== \"tool/result\") return;\n\tif (sourceRecord[\"kind\"] !== \"tool\" || typeof sourceRecord[\"callId\"] !== \"string\" || sourceRecord[\"callId\"] === \"\") throw new Error(`${subject} message must have tool source`);\n\tconst content = messageRecord[\"content\"];\n\tconst block = content[0];\n\tif (content.length !== 1 || typeof block !== \"object\" || block === null || block[\"type\"] !== \"tool-result\" || !Array.isArray(block[\"content\"])) throw new Error(`${subject} message must contain one tool-result block`);\n\tif (block[\"toolCallId\"] !== sourceRecord[\"callId\"]) throw new Error(`${subject} message has mismatched tool call ids`);\n}\n/** Whether an unknown value carries the current provider/model pair. */\nfunction hasProviderModel(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst pair = value;\n\treturn typeof pair[\"provider\"] === \"string\" && pair[\"provider\"].length > 0 && typeof pair[\"model\"] === \"string\" && pair[\"model\"].length > 0;\n}\n/** Reject request-header vocabulary removed with the legacy delta codec. */\nfunction assertSupportedRequestHeader(type, data, location) {\n\tif (type === \"request/header-delta\") throw new Error(`${location} uses unsupported legacy request/header-delta format`);\n\tif (type === \"request/header\" && data !== null && typeof data === \"object\" && !Array.isArray(data) && data[\"reason\"] === \"fallback\") throw new Error(`${location} uses unsupported legacy request/header reason \"fallback\"`);\n}\n/** Resolve one listener snapshot, including Cordis's internal dispatch checks. */\nfunction collectSessionCallbacks(ctx, args) {\n\treturn [...ctx.events.dispatch(\"emit\", args)];\n}\n/** Invoke one resolved observe-only listener snapshot with per-listener containment. */\nfunction invokeContainedSessionObservers(ctx, name, id, args, callbacks) {\n\tfor (const callback of callbacks) try {\n\t\tconst returned = callback(...args);\n\t\tPromise.resolve(returned).catch((error) => {\n\t\t\tctx.logger.warn(`session \"${id}\": ${name} listener rejected: ${String(error)}`);\n\t\t});\n\t} catch (error) {\n\t\tctx.logger.warn(`session \"${id}\": ${name} listener threw: ${String(error)}`);\n\t}\n}\n/** Store attachment for the append path; module-private to keep Session store-agnostic publicly. */\nconst attachments = /* @__PURE__ */ new WeakMap();\n/**\n* An event-sourced session: an append-only log of {@link SessionEvent}s.\n*\n* Plain class (not a Service) — create live instances via\n* `ctx.sessions.create()` and detached instances via {@link create}.\n* Seeding with an existing event log replays/forks a session.\n* @typert object\n*/\nvar Session = class Session {\n\tlog = [];\n\t/** Single incremental owner of surface acceptance and projection state. */\n\tsurfaceManager = new SurfaceManager(this.log);\n\t/** The ordered surface over this session's event log. */\n\tget surface() {\n\t\treturn this.surfaceManager;\n\t}\n\t/**\n\t* Detached, deep-frozen creation metadata (format version, cwd, lineage,\n\t* seed boundary). Supplied by the store via `ctx.sessions.create()`. When a\n\t* `Session` is created without a store-owned header, a minimal header is\n\t* synthesized (stamped with the current {@link SESSION_FORMAT_VERSION}) so\n\t* `session.header` is always present. Kept out of the event log — it is a\n\t* storage concern, not replayable conversation state.\n\t*/\n\theader;\n\t/** The session identity, derived from its durable header's single copy. */\n\tget id() {\n\t\treturn this.header.id;\n\t}\n\t/**\n\t* The first seq appended IN THIS PROCESS: the length of the constructor\n\t* seed (0 without one). Events with smaller seq values entered through\n\t* construction — replay, fork, or resume — and were never published on the\n\t* `session/event` firehose (constructor seeds do not emit), so consumers\n\t* that replay the log as a publication substitute (telemetry adoption)\n\t* start here. Distinct from `header.seedLength`, the DURABLE fork-lineage\n\t* boundary: a resumed session's constructor seed is its full stored log,\n\t* while its header keeps the original fork value — this field is the\n\t* in-process construction fact.\n\t*\n\t* Not persisted itself: a seeded session projects it into the log as the\n\t* `session/end-seed` event, which is what a consumer reading STORED history\n\t* reads. Locate the LAST such event, not necessarily one at this seq — a\n\t* seed already ending in one is not re-marked, so reopening an untouched\n\t* session leaves that event at a smaller seq than `firstLiveSeq`. Prefer\n\t* this field in-process: it is exact before the marker reaches storage.\n\t*\n\t* When this lifecycle appends the marker, it occupies this seq before the\n\t* store attaches and therefore does not publish either. Otherwise this seq\n\t* holds an ordinary published write.\n\t*/\n\tfirstLiveSeq;\n\t/**\n\t* Create a detached session by validating and snapshotting borrowed seed\n\t* events and storage metadata.\n\t* @param id - session identity.\n\t* @param seed - optional borrowed replay or fork events.\n\t* @param header - optional borrowed storage metadata.\n\t* @returns a detached session.\n\t*/\n\tstatic create(id, seed, header) {\n\t\treturn new Session(id, seed, header);\n\t}\n\t/**\n\t* Restore a detached session by taking ownership of fresh persistence values.\n\t* The storage format, event envelopes, sequence continuity, surface transitions,\n\t* and header fields are validated before the restored objects are frozen.\n\t* @param id - restored session identity.\n\t* @param seed - fresh detached events whose ownership is transferred.\n\t* @param header - fresh detached metadata whose ownership is transferred.\n\t* @returns a restored detached session.\n\t*/\n\tstatic fromRestore(id, seed, header) {\n\t\treturn new Session(id, seed, header, \"restore\");\n\t}\n\tconstructor(id, seed, header, mode = \"snapshot\") {\n\t\tconst restoredHeader = mode === \"restore\" ? validateRestoredSessionHeader(id, header) : void 0;\n\t\tif (seed !== void 0) for (const [index, source] of seed.entries()) {\n\t\t\tconst snapshot = mode === \"restore\" ? source : snapshotJsonValue(source);\n\t\t\tif (snapshot === void 0) throw new Error(`seed event at index ${index} is not losslessly JSON-serializable`);\n\t\t\tassertSessionEventEnvelope(snapshot, index);\n\t\t\tassertSupportedRequestHeader(snapshot.type, snapshot.data, `seed event at index ${index}`);\n\t\t\tif (snapshot.seq !== index) throw new Error(`seed event at index ${index} has seq ${snapshot.seq} (expected ${index}); seed must be contiguous from 0`);\n\t\t\ttry {\n\t\t\t\tthis.surfaceManager.validateNext(snapshot);\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(`invalid seed event at index ${index}: ${error instanceof Error ? error.message : \"invalid surface metadata\"}`);\n\t\t\t}\n\t\t\tthis.log.push(mode === \"restore\" ? freezeRestoredObject(snapshot) : deepFreeze(snapshot));\n\t\t}\n\t\tthis.firstLiveSeq = this.log.length;\n\t\tthis.header = restoredHeader ?? snapshotSessionHeader(id, header);\n\t\tif (seed !== void 0 && this.log.at(-1)?.type !== \"session/end-seed\") this.append(\"session/end-seed\", {});\n\t}\n\t/** Cached immutable public snapshot of the private append-only log. */\n\teventsSnapshot;\n\t/**\n\t* An immutable snapshot of the append-only event log. The snapshot is reused\n\t* until the next append; a previously returned array does not grow later.\n\t* Events and their nested data are deep-frozen at acceptance, so neither a\n\t* cast nor ordinary JavaScript can rewrite durable history.\n\t*/\n\tget events() {\n\t\tthis.eventsSnapshot ??= Object.freeze([...this.log]);\n\t\treturn this.eventsSnapshot;\n\t}\n\t/** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */\n\tget seq() {\n\t\treturn this.log.length;\n\t}\n\t/**\n\t* Append one typed event to the log and synchronously notify observers via\n\t* the store-owned, module-private publication hooks. The hot path never blocks\n\t* on I/O — persistence plugins buffer asynchronously. Once the event enters\n\t* the log, the append is committed: observer failures are logged and\n\t* contained per listener, so they do not change the return value or prevent\n\t* later listeners from observing the same accepted event.\n\t*\n\t* @param type - The event type (key of {@link SessionEventMap}).\n\t* @param data - The event payload; must be JSON-serializable.\n\t* @param opts - Surface metadata: `surfaceOp` controls how the event enters\n\t* the ordered surface; `sourceEventSeqs` lists the seq numbers of earlier\n\t* events this one derives from. REQUIRED for\n\t* {@link SurfaceEventType} events (every message-producing event must\n\t* declare how it joins the surface, the sole source of derived model\n\t* history) and\n\t* rejected by the compiler for non-surface types like `turn/start` or\n\t* `assistant/chunk`.\n\t* @returns the logged event — its assigned `seq`/`time` plus the SNAPSHOT of\n\t* `data` that entered the log, so reading `event.data` back sees the logged\n\t* value, never the caller's still-mutable input.\n\t* @throws if `data` or surface metadata is not losslessly JSON-serializable\n\t* (BigInt, function, symbol, undefined, negative zero, non-finite number,\n\t* circular reference, sparse array, or an exotic object such as\n\t* Map/Set/Date/class instance), or when the candidate violates the\n\t* canonical surface contract (marker shape and eligibility, unique\n\t* earlier source-event references, positional replacement validity, and complete\n\t* shadowed-node coverage). One recursive pass reads, validates, and\n\t* copies each nested value once, so a stateful getter cannot supply one value\n\t* to validation and another to storage. The event log is the durable source\n\t* of truth, so a bad event fails at the append site rather than later during\n\t* a backend flush. A synchronous internal dispatch validation failure or an\n\t* append reentered while this acceptance/publication boundary is open also\n\t* rejects before the log changes.\n\t*/\n\tappend(type, data, ...opts) {\n\t\tconst surfaceOpts = opts[0];\n\t\tconst surfaceMetadata = {\n\t\t\t...surfaceOpts?.sourceEventSeqs === void 0 ? {} : { sourceEventSeqs: surfaceOpts.sourceEventSeqs },\n\t\t\t...surfaceOpts?.surfaceOp === void 0 ? {} : { surfaceOp: surfaceOpts.surfaceOp }\n\t\t};\n\t\tconst dataSnapshot = snapshotJsonValue(data);\n\t\tif (dataSnapshot === void 0) throw new Error(`session event \"${type}\" carries non-JSON-serializable data`);\n\t\tassertSupportedRequestHeader(type, dataSnapshot, `session event \"${type}\"`);\n\t\tconst surfaceMetadataSnapshot = snapshotJsonValue(surfaceMetadata);\n\t\tif (surfaceMetadataSnapshot === void 0) throw new Error(`session event \"${type}\" carries non-JSON-serializable surface metadata`);\n\t\tconst entry = attachments.get(this);\n\t\tif (entry?.appending) throw new Error(\"session append cannot reenter while another append is being published\");\n\t\tconst event = deepFreeze({\n\t\t\ttype,\n\t\t\tseq: this.log.length,\n\t\t\ttime: Date.now(),\n\t\t\tdata: dataSnapshot,\n\t\t\t...surfaceMetadataSnapshot\n\t\t});\n\t\tthis.surfaceManager.validateNext(event);\n\t\tif (entry !== void 0) entry.appending = true;\n\t\ttry {\n\t\t\tlet callbacks;\n\t\t\tconst callbackArgs = [this, event];\n\t\t\tif (entry !== void 0) callbacks = collectSessionCallbacks(entry.emitCtx, [\n\t\t\t\tentry.carrier,\n\t\t\t\t\"session/event\",\n\t\t\t\t...callbackArgs\n\t\t\t]);\n\t\t\tthis.log.push(event);\n\t\t\tthis.eventsSnapshot = void 0;\n\t\t\tif (callbacks !== void 0 && entry !== void 0) invokeContainedSessionObservers(entry.emitCtx, \"session/event\", entry.id, callbackArgs, callbacks);\n\t\t\treturn event;\n\t\t} finally {\n\t\t\tif (entry !== void 0) {\n\t\t\t\tentry.appending = false;\n\t\t\t\tif (entry.detachRequested && !entry.announcing) entry.detach();\n\t\t\t}\n\t\t}\n\t}\n\t/** Cached fold of the request-header events — see {@link requestHeader}. */\n\theaderFold;\n\t/** Log position (events consumed) the header fold has reached. */\n\theaderFoldSeq = 0;\n\t/**\n\t* The {@link EpochHeader} in force after the log's last header event — the\n\t* header the NEXT request will be compared against — or undefined before\n\t* the first `request/header` snapshot. The live, incrementally-maintained\n\t* form of `foldRequestHeader(session.events)`: each header event is folded\n\t* once, when first seen, so a per-step read costs O(new events).\n\t* @returns the folded header, or undefined when no header event exists yet.\n\t*/\n\trequestHeader() {\n\t\tif (this.headerFoldSeq < this.log.length) {\n\t\t\tthis.headerFold = deepFreeze(foldRequestHeader(this.log.slice(this.headerFoldSeq), this.headerFold));\n\t\t\tthis.headerFoldSeq = this.log.length;\n\t\t}\n\t\treturn this.headerFold;\n\t}\n\t/** Cached fold of `request/context` events. */\n\tcontextFold;\n\tcontextFoldSeq = 0;\n\t/**\n\t* Return the latest resolved route metadata, or `undefined` before the first\n\t* `request/context` event. Each event is folded once.\n\t* @returns the latest immutable route metadata.\n\t*/\n\trequestContext() {\n\t\tif (this.contextFoldSeq < this.log.length) {\n\t\t\tfor (const event of this.log.slice(this.contextFoldSeq)) if (event.type === \"request/context\") this.contextFold = deepFreeze({ ...event.data });\n\t\t\tthis.contextFoldSeq = this.log.length;\n\t\t}\n\t\treturn this.contextFold;\n\t}\n\t/** The derived-message cache: frozen projections, extended per unseen node. */\n\tderived = [];\n\t/** Surface position (nodes projected) the cache has reached. */\n\tderivedNodes = 0;\n\t/** {@link SurfaceManager.replaceGeneration} the cache was built under. */\n\tderivedGeneration = 0;\n\t/**\n\t* Derive the LLM message history by walking the ordered sequences of\n\t* message-producing events maintained by `surfaceOp` markers. The\n\t* surface is the single source of derived history: every message-producing\n\t* append records its `surfaceOp`, so a raw event with no marker (a chunk, a\n\t* turn boundary) is correctly absent, and a compaction `replace` deletes the\n\t* shadowed nodes from the derivation. The projection rules are\n\t* {@link deriveEventMessage}, folded per node.\n\t*\n\t* CACHED: each surface node is projected exactly once, when first seen — a\n\t* call costs O(new nodes), and a surface rewrite (a `replace`;\n\t* {@link SessionSurface.replaceGeneration}) rebuilds. The returned array is\n\t* a fresh snapshot per call (later appends never grow an array a caller\n\t* already holds); the `Message` objects in it are SHARED and **deep-frozen**.\n\t* Their content reuses the already frozen durable event data, so the cache\n\t* needs no second deep clone and consumers still cannot mutate the log.\n\t* @returns a fresh array of the shared, frozen derived history.\n\t*/\n\tderiveMessages() {\n\t\tconst surface = this.surface;\n\t\tconst nodes = surface.nodes;\n\t\tconst generation = surface.replaceGeneration;\n\t\tif (generation !== this.derivedGeneration) {\n\t\t\tthis.derived = [];\n\t\t\tthis.derivedNodes = 0;\n\t\t\tthis.derivedGeneration = generation;\n\t\t}\n\t\tfor (const seq of nodes.slice(this.derivedNodes)) {\n\t\t\tconst msg = this.deriveEventMessage(this.log[seq]);\n\t\t\tif (msg) this.derived.push(msg);\n\t\t}\n\t\tthis.derivedNodes = nodes.length;\n\t\treturn [...this.derived];\n\t}\n\t/**\n\t* Instance face of the pure per-node `deriveEventMessage` export from\n\t* `surface.ts`.\n\t* @param event - the event to project.\n\t* @returns the derived message, or null when the event produces none.\n\t*/\n\tderiveEventMessage(event) {\n\t\treturn deriveEventMessage(event);\n\t}\n};\n/** Typed error for session fork rejections. */\nvar SessionForkError = class extends Error {\n\tcode;\n\tconstructor(message, code) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.name = \"SessionForkError\";\n\t}\n};\n/**\n* In-memory session store (`ctx.sessions`).\n*\n* Persistence is intentionally not implemented here — persistence plugins\n* subscribe to `session/event` and flush on `session/flush` / dispose.\n*/\nvar SessionStore = class extends Service {\n\tstore = /* @__PURE__ */ new Map();\n\tcounter = 0;\n\tconstructor(ctx) {\n\t\tsuper(ctx, \"sessions\");\n\t\tctx.inject([\"typert\"], (typeCtx) => {\n\t\t\ttypeCtx.typert.lookups.register(\"session\", {\n\t\t\t\tparameter: \"session\",\n\t\t\t\twire: \"sessionId\",\n\t\t\t\thostTypeSymbol: \"@deepseek-ai/dsh-session#Session\",\n\t\t\t\twireTypeSymbol: \"@deepseek-ai/dsh-session/types#SessionId\",\n\t\t\t\tresolve: (sessionId) => this.get(sessionId)\n\t\t\t});\n\t\t});\n\t}\n\t/**\n\t* Create a session owned by the calling fiber: disposing that fiber stops\n\t* event notification and removes the session from the store. `options.seed`\n\t* populates the session with a copy of those events (replay/fork);\n\t* `options.meta` attaches creation metadata (validated absolute `cwd`, seed\n\t* and parent lineage, and delegation depth) as the immutable\n\t* {@link SessionHeader} (the store fills `version`/`id`/`createdAt`).\n\t*\n\t* For an agent whose session must be torn down IN ORDER with its loop (so the\n\t* loop's final events are published before the store attachment ends), do NOT use this\n\t* — fold the session lifecycle into the agent's own effect via\n\t* {@link prepare} + {@link enter} + {@link announce} (see\n\t* `dsh-agent-loop`'s creation transaction).\n\t*\n\t* @param id - the session id; omitted, the store mints `session-<n>`.\n\t* @param options - seed events and/or creation metadata for the header.\n\t* @returns the live session, already entered and announced.\n\t* @throws if a session with `id` already exists, metadata is not a plain\n\t* lossless-JSON record with valid scalar fields, or `meta.cwd` is a\n\t* non-absolute path (storage backends key directories off it).\n\t*/\n\tcreate(id, options) {\n\t\tconst session = this.prepare(id, options);\n\t\tthis.ctx.effect(function* () {\n\t\t\tyield this.enter(session);\n\t\t\tthis.announce(session);\n\t\t}.bind(this), \"sessions.create()\");\n\t\treturn session;\n\t}\n\t/**\n\t* Build a session WITHOUT entering it into the store — validate the id/cwd and\n\t* construct the {@link Session} (with its immutable {@link SessionHeader}).\n\t* Pairs with {@link enter} + {@link announce}: a caller that owns a composite\n\t* `ctx.effect` (the agent factory) folds the session lifecycle into that ONE\n\t* effect so a fiber unload tears the session + agent down as a single ORDERED\n\t* chain rather than as racing sibling effects — which would remove the publication hooks\n\t* before the driver's closing events commit, dropping them.\n\t*\n\t* @param id - the session id; omitted, the store mints `session-<n>`.\n\t* @param options - seed events and/or creation metadata for the header. With\n\t* `seedSource: 'persistence'`, metadata and events must be fresh detached\n\t* graphs whose ownership transfers to this call: they are validated and\n\t* frozen in place through {@link Session.fromRestore}, so the caller must\n\t* retain no mutable aliases.\n\t* @returns the constructed session, NOT yet in the store.\n\t* @throws if a session with `id` already exists, metadata is not a plain\n\t* lossless-JSON record with valid scalar fields, or `meta.cwd` is a\n\t* non-absolute path.\n\t*/\n\tprepare(id, options) {\n\t\tlet sessionId;\n\t\tif (id === void 0) do\n\t\t\tsessionId = SessionId(`session-${++this.counter}`);\n\t\twhile (this.store.has(sessionId));\n\t\telse sessionId = SessionId(id);\n\t\tif (this.store.has(sessionId)) throw new Error(`session \"${sessionId}\" already exists`);\n\t\tif (options?.seedSource === \"persistence\") return Session.fromRestore(sessionId, options.seed, options.meta);\n\t\tconst seed = options?.seed;\n\t\tconst meta = options?.meta;\n\t\tconst header = {\n\t\t\tversion: 0,\n\t\t\tid: sessionId,\n\t\t\tcreatedAt: meta?.createdAt ?? Date.now(),\n\t\t\t...meta?.cwd === void 0 ? {} : { cwd: meta.cwd },\n\t\t\t...meta?.parentSession === void 0 ? {} : { parentSession: meta.parentSession },\n\t\t\t...meta?.seedLength === void 0 ? {} : { seedLength: meta.seedLength },\n\t\t\t...meta?.origin === void 0 ? {} : { origin: meta.origin },\n\t\t\t...meta?.delegationDepth === void 0 ? {} : { delegationDepth: meta.delegationDepth },\n\t\t\t...meta?.agentPreset === void 0 ? {} : { agentPreset: meta.agentPreset }\n\t\t};\n\t\treturn Session.create(sessionId, seed, header);\n\t}\n\t/**\n\t* Enter a {@link prepare}d session into the store: install the module-private\n\t* append publication hooks and add it to the store. Returns the DETACH\n\t* disposer (hooks + store removal). Does NOT emit `session/created` —\n\t* the caller yields this disposer inside its effect and THEN calls\n\t* {@link announce}, so a throwing `session/created` listener rolls the attach\n\t* back instead of leaking it.\n\t*\n\t* Re-checks the id for a duplicate: `prepare` and `enter` are public\n\t* cross-package primitives and a caller may interleave arbitrary work (or\n\t* another create) between them, so a stale prepared session must NOT overwrite\n\t* a live store entry of the same id — its detach disposer would later delete\n\t* the REAL session. The {@link create} convenience and the agent factory call\n\t* the two back-to-back so they never trip this, but the public API cannot\n\t* assume that.\n\t*\n\t* @param session - a {@link prepare}d session not yet in the store.\n\t* @returns the detach disposer (publication hooks + store removal). When called from\n\t* a synchronous `session/created` listener, removal and disposal wait until\n\t* that creation dispatch unwinds.\n\t* @throws if a session with this id is already in the store.\n\t*/\n\tenter(session) {\n\t\tconst id = session.id;\n\t\tconst carrier = scopeTarget(session, scopeOf(this.ctx));\n\t\tif (this.store.has(id)) throw new Error(`session \"${id}\" already exists`);\n\t\tif (attachments.has(session)) throw new Error(`session \"${id}\" is already attached to a store`);\n\t\tconst entry = {\n\t\t\tid,\n\t\t\tsession,\n\t\t\tcarrier,\n\t\t\temitCtx: this.ctx,\n\t\t\tannounced: false,\n\t\t\tannouncing: false,\n\t\t\tappending: false,\n\t\t\tdetachRequested: false,\n\t\t\tdetach: () => {\n\t\t\t\tthis.detachEntered(entry);\n\t\t\t}\n\t\t};\n\t\tthis.store.set(id, entry);\n\t\tattachments.set(session, entry);\n\t\tlet entered = true;\n\t\tconst detach = () => {\n\t\t\tif (!entered) return;\n\t\t\tentered = false;\n\t\t\tif (entry.announcing || entry.appending) {\n\t\t\t\tentry.detachRequested = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tentry.detach();\n\t\t};\n\t\treturn detach;\n\t}\n\t/** Remove one exact entered session and emit its paired disposal when announced. */\n\tdetachEntered(entry) {\n\t\tentry.detachRequested = false;\n\t\t/* v8 ignore next -- enter() rejects replacement while this single-shot detach capability is live. */\n\t\tif (this.store.get(entry.id) !== entry) return;\n\t\tthis.store.delete(entry.id);\n\t\tattachments.delete(entry.session);\n\t\tif (entry.announced) this.emitDisposed(entry);\n\t}\n\t/** Emit `session/created` exactly once for an {@link enter}ed session (with\n\t* the carrier {@link enter} captured). Separate from {@link enter} so the\n\t* caller can yield the detach disposer first (rollback safety — see\n\t* {@link enter}).\n\t* @param session - the entered session to announce to listeners.\n\t* @throws if the session is not live or its announcement already began,\n\t* including a reentrant call from a creation listener. */\n\tannounce(session) {\n\t\tconst entry = this.liveEntryFor(session);\n\t\tif (entry.announced || entry.announcing) throw new Error(`session \"${entry.id}\" was already announced`);\n\t\tentry.announced = true;\n\t\tconst callbackArgs = [session];\n\t\tentry.announcing = true;\n\t\ttry {\n\t\t\tconst callbacks = collectSessionCallbacks(this.ctx, [\n\t\t\t\tentry.carrier,\n\t\t\t\t\"session/created\",\n\t\t\t\tsession\n\t\t\t]);\n\t\t\tfor (const callback of callbacks) {\n\t\t\t\tconst returned = callback(...callbackArgs);\n\t\t\t\tPromise.resolve(returned).catch((error) => {\n\t\t\t\t\tthis.ctx.logger.warn(`session \"${entry.id}\": session/created listener rejected: ${String(error)}`);\n\t\t\t\t});\n\t\t\t}\n\t\t} finally {\n\t\t\tentry.announcing = false;\n\t\t\tif (entry.detachRequested && !entry.appending) entry.detach();\n\t\t}\n\t}\n\t/** Emit the paired teardown notification with per-listener containment. */\n\temitDisposed(entry) {\n\t\tconst callbackArgs = [entry.session];\n\t\ttry {\n\t\t\tconst callbacks = collectSessionCallbacks(this.ctx, [\n\t\t\t\tentry.carrier,\n\t\t\t\t\"session/disposed\",\n\t\t\t\tentry.session\n\t\t\t]);\n\t\t\tinvokeContainedSessionObservers(this.ctx, \"session/disposed\", entry.id, callbackArgs, callbacks);\n\t\t} catch (error) {\n\t\t\tthis.ctx.logger.warn(`session \"${entry.id}\": session/disposed dispatch threw: ${String(error)}`);\n\t\t}\n\t}\n\t/**\n\t* Dispatch the awaited `session/flush` durability checkpoint for `session`,\n\t* with the carrier captured at {@link enter}. THE flush entry point: the\n\t* store owns the carrier, so callers (the checkpoint policy's per-request\n\t* barrier, goal-round-driver's idle checkpoint, teardown drains, and consumers\n\t* that flush themselves before reading storage) must come through here\n\t* rather than dispatch a raw `ctx.parallel('session/flush', …)` — one owner,\n\t* one spelling, and the scoped-dispatch invariant can pin it.\n\t* @param session - the session whose buffered events must reach durable storage.\n\t* @returns whether at least one durability listener participated, after every\n\t* listener has settled successfully.\n\t* @throws the first registered listener failure after every listener settles.\n\t*/\n\tasync flush(session) {\n\t\tconst { carrier } = this.liveEntryFor(session);\n\t\tconst callbackArgs = [session];\n\t\tconst callbacks = collectSessionCallbacks(this.ctx, [\n\t\t\tcarrier,\n\t\t\t\"session/flush\",\n\t\t\tsession\n\t\t]);\n\t\tconst failure = (await Promise.allSettled(callbacks.map((callback) => {\n\t\t\ttry {\n\t\t\t\treturn callback(...callbackArgs);\n\t\t\t} catch (error) {\n\t\t\t\treturn Promise.reject(error);\n\t\t\t}\n\t\t}))).find((result) => result.status === \"rejected\");\n\t\tif (failure !== void 0) throw failure.reason;\n\t\treturn callbacks.length > 0;\n\t}\n\t/** Return the exact live entry; detached/prepared objects reject. */\n\tliveEntryFor(session) {\n\t\tconst entry = attachments.get(session);\n\t\tif (entry === void 0 || this.store.get(entry.id) !== entry) throw new Error(`session \"${session.id}\" is not live in this store`);\n\t\treturn entry;\n\t}\n\t/**\n\t* Look up a live session.\n\t* @param id - the session id to look up.\n\t* @returns the session, or undefined when no live session has that id.\n\t*/\n\tget(id) {\n\t\treturn this.store.get(id)?.session;\n\t}\n\t/**\n\t* All live sessions, in creation order.\n\t* @returns a fresh array; mutating it does not affect the store.\n\t*/\n\tlist() {\n\t\treturn [...this.store.values()].map((entry) => entry.session);\n\t}\n\t/**\n\t* Create a live child session from a stable prefix of a live source.\n\t* `boundary` is an inclusive source event seq; omitted means the source's\n\t* current last event. The selected slice may end with a between-turn event\n\t* but must not end inside an open turn.\n\t*\n\t* @param source - Live source session object or id.\n\t* @param boundary - Inclusive source event seq to fork through; omitted means\n\t* the source's current last event, and omitted on an empty source forks an\n\t* empty child.\n\t* @param childSessionId - Optional child session id; omitted delegates to\n\t* `SessionStore`'s id policy.\n\t* @returns The created live child session.\n\t*/\n\tfork(source, boundary, childSessionId) {\n\t\tif (childSessionId !== void 0 && this.get(childSessionId) !== void 0) throw new SessionForkError(`session \"${childSessionId}\" already exists`, \"SESSION_ALREADY_EXISTS\");\n\t\tconst liveSource = this._resolveForkSource(source);\n\t\tconst seed = this._forkSeed(liveSource, boundary);\n\t\treturn this.create(childSessionId, {\n\t\t\tseed,\n\t\t\tmeta: {\n\t\t\t\t...liveSource.header.cwd !== void 0 ? { cwd: liveSource.header.cwd } : {},\n\t\t\t\tparentSession: liveSource.id,\n\t\t\t\tseedLength: seed.length\n\t\t\t}\n\t\t});\n\t}\n\t_forkSeed(session, requestedBoundary) {\n\t\tconst events = session.events;\n\t\tconst lastEvent = events.at(-1);\n\t\tlet boundary;\n\t\tif (requestedBoundary !== void 0) boundary = requestedBoundary;\n\t\telse {\n\t\t\tif (lastEvent === void 0) return [];\n\t\t\tboundary = lastEvent.seq;\n\t\t}\n\t\tif (!Number.isSafeInteger(boundary) || boundary < 0) throw new SessionForkError(`fork boundary for session \"${session.id}\" must be a non-negative safe integer, got ${String(boundary)}`, \"INVALID_BOUNDARY\");\n\t\tif (boundary >= events.length) {\n\t\t\tconst lastSeq = events.at(-1)?.seq;\n\t\t\tthrow new SessionForkError(`fork boundary ${boundary} does not exist in session \"${session.id}\" (last seq: ${lastSeq ?? \"none\"})`, \"INVALID_BOUNDARY\");\n\t\t}\n\t\tconst boundaryEvent = events[boundary];\n\t\tif (boundaryEvent === void 0 || boundaryEvent.seq !== boundary) throw new SessionForkError(`fork boundary ${boundary} does not match a contiguous event seq in session \"${session.id}\"`, \"INVALID_BOUNDARY\");\n\t\tconst lastTurnBoundary = events.slice(0, boundary + 1).findLast((event) => event.type === \"turn/start\" || event.type === \"turn/end\");\n\t\tif (lastTurnBoundary?.type === \"turn/start\") throw new SessionForkError(`fork boundary ${boundary} in session \"${session.id}\" ends inside open turn ${lastTurnBoundary.data.turn}`, \"OPEN_TURN\");\n\t\treturn events.slice(0, boundary + 1);\n\t}\n\t_resolveForkSource(source) {\n\t\tif (typeof source === \"string\") {\n\t\t\tconst session = this.get(source);\n\t\t\tif (session === void 0) throw new SessionForkError(`session \"${source}\" not found`, \"SESSION_NOT_FOUND\");\n\t\t\treturn session;\n\t\t}\n\t\tconst live = this.get(source.id);\n\t\tif (live === void 0) throw new SessionForkError(`session \"${source.id}\" not found`, \"SESSION_NOT_FOUND\");\n\t\tif (live !== source) throw new SessionForkError(`session \"${source.id}\" is not the live store instance`, \"SESSION_NOT_LIVE\");\n\t\treturn source;\n\t}\n};\n//#endregion\nexport { KNOWN_SESSION_EVENT_TYPES, SESSION_FORMAT_VERSION, Session, SessionForkError, SessionId, SessionPreparation, SessionStore, SessionStore as default, TOOL_NOT_STARTED, TOOL_OUTCOME_UNKNOWN, adoptSessionEvent, canonicalHeader, decodeStorageRecord, deriveEventMessage, foldRequestHeader, foldSurface, headerEquals, interruptedTurnClosers, isAppendSurfaceEvent, isJsonValue, isReplacementSurfaceEvent, isSurfaceEligibleType, isSurfaceEvent, packChunkRuns, snapshotJsonValue, snapshotSessionEvent };\n","import { Service } from \"@deepseek-ai/cordis\";\nimport z from \"@deepseek-ai/schemastery\";\nimport { AnonymousEntries, NamedEntries, ScopedLayers, scopeOf, scopeTarget } from \"@deepseek-ai/dsh-scope\";\nimport { CallId, HarnessError, assertNever, deepFreeze } from \"@deepseek-ai/dsh-llm\";\nimport { isJsonValue, snapshotJsonValue } from \"@deepseek-ai/dsh-session\";\n//#region lib/types/json-schema.js\n/**\n* Enforced JSON Schema subset shared by tool outputs, generated Code Mode\n* types, subagents, and workflows. The subset accepts any JSON root, an\n* annotation-only schema for unconstrained JSON, one scalar `type`, object\n* `properties`/`required`/boolean `additionalProperties`, array `items`,\n* type-correct scalar `enum`/`const`, and exact-one `oneOf`.\n*\n* Unsupported or misplaced keywords reject rather than being accepted without\n* enforcement. Consumers that require an object root apply\n* {@link assertObjectJsonSchema} before accepting input.\n* @module dsh-tools/json-schema\n*/\n/**\n* Thrown when a raw schema falls outside the enforced subset. `violations`\n* lists every offending path instead of stopping at the first author error.\n*/\nvar JsonSchemaError = class extends HarnessError {\n\t/** Individual schema violations in walk order. */\n\tviolations;\n\tconstructor(violations) {\n\t\tsuper(`unsupported JSON schema: ${violations.join(\"; \")}`, \"UNSUPPORTED_SCHEMA\");\n\t\tthis.name = \"JsonSchemaError\";\n\t\tthis.violations = violations;\n\t}\n};\nconst CONSTRAINT_KEYWORDS = new Set([\n\t\"type\",\n\t\"oneOf\",\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n]);\nconst ANNOTATION_KEYWORDS = new Set([\n\t\"description\",\n\t\"title\",\n\t\"default\",\n\t\"examples\"\n]);\nconst SCHEMA_TYPES = [\n\t\"object\",\n\t\"array\",\n\t\"string\",\n\t\"number\",\n\t\"integer\",\n\t\"boolean\",\n\t\"null\"\n];\n/** Whether a realm-owned intrinsic prototype is backed by its native constructor. */\nfunction hasIntrinsicConstructor(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, \"Object\");\n}\n/**\n* Test for a realm-agnostic plain JSON record without accepting arrays or\n* exotic objects.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the value has a plain-object prototype chain.\n*/\nfunction isPlainJsonRecord(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\ttry {\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype(prototype);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`. */\nfunction hasPlainArrayPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);\n}\n/** Return whether a record contains only own enumerable string keys. */\nfunction hasOnlyEnumerableStringKeys(value) {\n\ttry {\n\t\treturn Reflect.ownKeys(value).every((key) => typeof key === \"string\" && Object.prototype.propertyIsEnumerable.call(value, key));\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Test for an ordinary schema record whose keys survive JSON projection.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the record has an intrinsic prototype and only own enumerable string keys.\n*/\nfunction isJsonSchemaRecord(value) {\n\treturn isPlainJsonRecord(value) && hasOnlyEnumerableStringKeys(value);\n}\n/**\n* Test for a dense ordinary array with no JSON-invisible decorations.\n* @param value - candidate array from any JavaScript realm.\n* @returns Whether the array is intrinsic, dense, and undecorated.\n*/\nfunction isPlainJsonArray(value) {\n\tif (!Array.isArray(value)) return false;\n\ttry {\n\t\tif (!hasPlainArrayPrototype(value) || Reflect.ownKeys(value).length !== value.length + 1) return false;\n\t\tfor (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) return false;\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Lossless finite JSON number, excluding negative zero. */\nfunction isJsonNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && !Object.is(value, -0);\n}\n/** Whether a scalar is valid for one declared schema type. */\nfunction scalarMatches(type, value) {\n\tswitch (type) {\n\t\tcase \"string\": return typeof value === \"string\";\n\t\tcase \"number\": return isJsonNumber(value);\n\t\tcase \"integer\": return isJsonNumber(value) && Number.isInteger(value);\n\t\tcase \"boolean\": return typeof value === \"boolean\";\n\t\tcase \"null\": return value === null;\n\t\t/* v8 ignore next -- JsonSchemaScalarType is closed; this retains compile-time exhaustiveness. */\n\t\tdefault: return assertNever(type, \"JsonSchemaType\");\n\t}\n}\n/** Keywords that are invalid beside `oneOf`. */\nconst ONE_OF_SIBLING_KEYWORDS = [\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n];\n/** Validate object-only fields after its property schemas have been visited. */\nfunction checkObjectSchemaTail(node, path, properties, violations) {\n\tconst hasRequired = Object.hasOwn(node, \"required\");\n\tconst required = hasRequired ? node.required : void 0;\n\tif (hasRequired) if (!isPlainJsonArray(required) || required.some((entry) => typeof entry !== \"string\")) violations.push(`${path}.required must be an array of strings`);\n\telse {\n\t\tconst declared = isJsonSchemaRecord(properties) ? properties : {};\n\t\tfor (const key of required) if (!Object.hasOwn(declared, key)) violations.push(`${path}.required names \"${key}\" which is not in properties`);\n\t}\n\tif (Object.hasOwn(node, \"additionalProperties\") && typeof node.additionalProperties !== \"boolean\") violations.push(`${path}.additionalProperties must be a boolean`);\n}\n/** Collect every violation for one raw schema tree without using the JavaScript call stack. */\nfunction checkSchemaNode(root, rootPath, violations, seen) {\n\tconst tasks = [{\n\t\tkind: \"enter\",\n\t\tnode: root,\n\t\tpath: rootPath\n\t}];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (task.kind === \"leave\") {\n\t\t\tseen.delete(task.node);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"one-of-tail\") {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(task.node, key)) violations.push(`${task.path}.${key} is not supported beside oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"object-tail\") {\n\t\t\tcheckObjectSchemaTail(task.node, task.path, task.properties, violations);\n\t\t\tcontinue;\n\t\t}\n\t\tconst { node, path } = task;\n\t\tif (!isJsonSchemaRecord(node)) {\n\t\t\tviolations.push(`${path} must be a schema object`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (seen.has(node)) {\n\t\t\tviolations.push(`${path} is circular`);\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(node);\n\t\ttasks.push({\n\t\t\tkind: \"leave\",\n\t\t\tnode\n\t\t});\n\t\tfor (const key of Object.keys(node)) {\n\t\t\tif (CONSTRAINT_KEYWORDS.has(key)) continue;\n\t\t\tif (ANNOTATION_KEYWORDS.has(key)) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!isJsonValue(node[key])) violations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t} catch {\n\t\t\t\t\tviolations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tviolations.push(`${path}.${key} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`);\n\t\t}\n\t\tif (Object.hasOwn(node, \"description\") && typeof node.description !== \"string\") violations.push(`${path}.description must be a string`);\n\t\tif (Object.hasOwn(node, \"title\") && typeof node.title !== \"string\") violations.push(`${path}.title must be a string`);\n\t\tconst hasType = Object.hasOwn(node, \"type\");\n\t\tconst hasOneOf = Object.hasOwn(node, \"oneOf\");\n\t\tif (hasType && hasOneOf) {\n\t\t\tviolations.push(`${path} cannot declare both type and oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasType && !hasOneOf) {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(node, key)) violations.push(`${path}.${key} requires type or oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (hasOneOf) {\n\t\t\tconst oneOf = node.oneOf;\n\t\t\ttasks.push({\n\t\t\t\tkind: \"one-of-tail\",\n\t\t\t\tnode,\n\t\t\t\tpath\n\t\t\t});\n\t\t\tif (!isPlainJsonArray(oneOf) || oneOf.length < 2) violations.push(`${path}.oneOf must be an array of at least two schemas`);\n\t\t\telse for (let index = oneOf.length - 1; index >= 0; index--) tasks.push({\n\t\t\t\tkind: \"enter\",\n\t\t\t\tnode: oneOf[index],\n\t\t\t\tpath: `${path}.oneOf[${index}]`\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst type = node.type;\n\t\tif (typeof type !== \"string\" || !SCHEMA_TYPES.includes(type)) {\n\t\t\tviolations.push(Array.isArray(type) ? `${path}.type must be a single type string (type arrays are not supported)` : `${path}.type must be one of ${SCHEMA_TYPES.join(\"/\")}`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst schemaType = type;\n\t\tfor (const [key, types] of Object.entries({\n\t\t\tproperties: [\"object\"],\n\t\t\trequired: [\"object\"],\n\t\t\tadditionalProperties: [\"object\"],\n\t\t\titems: [\"array\"],\n\t\t\tenum: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t],\n\t\t\tconst: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t]\n\t\t})) if (Object.hasOwn(node, key) && !types.includes(schemaType)) violations.push(`${path}.${key} is not supported on type \"${schemaType}\"`);\n\t\tswitch (schemaType) {\n\t\t\tcase \"object\": {\n\t\t\t\tconst properties = Object.hasOwn(node, \"properties\") ? node.properties : void 0;\n\t\t\t\ttasks.push({\n\t\t\t\t\tkind: \"object-tail\",\n\t\t\t\t\tnode,\n\t\t\t\t\tpath,\n\t\t\t\t\tproperties\n\t\t\t\t});\n\t\t\t\tif (Object.hasOwn(node, \"properties\")) if (!isJsonSchemaRecord(properties)) violations.push(`${path}.properties must be an object of schemas`);\n\t\t\t\telse {\n\t\t\t\t\tconst entries = Object.entries(properties);\n\t\t\t\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\t\t\t\tconst entry = entries[index];\n\t\t\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured entry count. */\n\t\t\t\t\t\tif (entry === void 0) continue;\n\t\t\t\t\t\ttasks.push({\n\t\t\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\t\t\tnode: entry[1],\n\t\t\t\t\t\t\tpath: `${path}.properties.${entry[0]}`\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"array\":\n\t\t\t\tif (Object.hasOwn(node, \"items\")) tasks.push({\n\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\tnode: node.items,\n\t\t\t\t\tpath: `${path}.items`\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"string\":\n\t\t\tcase \"number\":\n\t\t\tcase \"integer\":\n\t\t\tcase \"boolean\":\n\t\t\tcase \"null\": {\n\t\t\t\tconst hasEnum = Object.hasOwn(node, \"enum\");\n\t\t\t\tconst allowed = hasEnum ? node.enum : void 0;\n\t\t\t\tconst enumValid = isPlainJsonArray(allowed) && allowed.length > 0 && allowed.every((entry) => scalarMatches(schemaType, entry));\n\t\t\t\tif (hasEnum && !enumValid) violations.push(`${path}.enum must be a non-empty array of ${schemaType} values`);\n\t\t\t\tconst hasConst = Object.hasOwn(node, \"const\");\n\t\t\t\tconst declaredConst = hasConst ? node.const : void 0;\n\t\t\t\tconst constValid = scalarMatches(schemaType, declaredConst);\n\t\t\t\tif (hasConst) {\n\t\t\t\t\tif (!constValid) violations.push(`${path}.const must be a ${schemaType} value`);\n\t\t\t\t\telse if (enumValid && !allowed.includes(declaredConst)) violations.push(`${path}.const must be one of ${path}.enum when both are declared`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* v8 ignore next -- schemaType was narrowed from the closed SCHEMA_TYPES table above. */\n\t\t\tdefault: assertNever(schemaType, \"JsonSchemaType\");\n\t\t}\n\t}\n}\n/**\n* Assert that an arbitrary raw schema uses only the enforced subset.\n* Annotation-only schemas are accepted as the standard unconstrained-JSON\n* form; callers that require an object root use {@link assertObjectJsonSchema}.\n* @param schema - untrusted raw JSON Schema.\n* @returns Assertion that the schema belongs to the supported subset.\n*/\nfunction assertSupportedJsonSchema(schema) {\n\tconst violations = [];\n\tcheckSchemaNode(schema, \"schema\", violations, /* @__PURE__ */ new Set());\n\tif (violations.length > 0) throw new JsonSchemaError(violations);\n}\n/**\n* Assert the enforced subset plus the object-root constraint retained by\n* subagent and workflow structured outputs.\n* @param schema - untrusted caller-supplied schema.\n* @returns Assertion that the schema belongs to the supported subset and has an object root.\n*/\nfunction assertObjectJsonSchema(schema) {\n\tconst violations = [];\n\tcheckSchemaNode(schema, \"schema\", violations, /* @__PURE__ */ new Set());\n\tif (violations.length === 0 && (!isJsonSchemaRecord(schema) || !Object.hasOwn(schema, \"type\") || schema.type !== \"object\")) violations.push(\"schema.type must be \\\"object\\\" (structured output is object-rooted)\");\n\tif (violations.length > 0) throw new JsonSchemaError(violations);\n}\n/** Safely test the lossless JSON boundary when a getter may throw. */\nfunction safelyIsJsonValue(value) {\n\ttry {\n\t\treturn isJsonValue(value);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Root-aware diagnostic path for the parameter validator's empty sentinel. */\nfunction diagnosticPath(path) {\n\treturn path === \"\" ? \"arguments\" : path;\n}\n/** Append one object property without a leading dot at an implicit root. */\nfunction propertyPath(path, key) {\n\treturn path === \"\" ? key : `${path}.${key}`;\n}\n/** The generic exception-containment diagnostic owned by one valid schema node. */\nfunction losslessValueViolation(path) {\n\treturn [`\"${diagnosticPath(path)}\" must be a lossless JSON value`];\n}\n/** Append diagnostics without spreading a potentially wide child result as call arguments. */\nfunction appendViolations(target, source) {\n\tfor (const violation of source) target.push(violation);\n}\n/** Initialize one validation frame with empty aggregation state. */\nfunction valueFrame(node, value, path) {\n\treturn {\n\t\tnode,\n\t\tvalue,\n\t\tpath,\n\t\tcatches: false,\n\t\tphase: \"start\",\n\t\tchildren: [],\n\t\tchildIndex: 0,\n\t\tviolations: [],\n\t\ttailViolations: [],\n\t\tmatches: 0\n\t};\n}\n/** Validate one scalar node after its primitive type check. */\nfunction checkScalarValue(node, value, path) {\n\tconst allowed = Object.hasOwn(node, \"enum\") ? node.enum : void 0;\n\tif (allowed !== void 0 && !allowed.includes(value)) return [`\"${diagnosticPath(path)}\" must be one of ${JSON.stringify(allowed)}`];\n\tif (Object.hasOwn(node, \"const\") && value !== node.const) return [`\"${diagnosticPath(path)}\" must be ${JSON.stringify(node.const)}`];\n\treturn [];\n}\n/** Validate one trusted schema/value pair with explicit frames rather than recursive calls. */\nfunction checkValue(schema, value, path) {\n\tconst frames = [valueFrame(schema, value, path)];\n\tlet rootResult;\n\tconst receive = (result) => {\n\t\tconst parent = frames.at(-1);\n\t\tif (parent === void 0) {\n\t\t\trootResult = result;\n\t\t\treturn;\n\t\t}\n\t\tif (parent.kind === \"oneOf\") {\n\t\t\tif (result.length === 0) parent.matches++;\n\t\t} else appendViolations(parent.violations, result);\n\t};\n\tconst finish = (result) => {\n\t\tframes.pop();\n\t\treceive(result);\n\t};\n\twhile (frames.length > 0) {\n\t\tconst frame = frames.at(-1);\n\t\t/* v8 ignore next -- the loop condition guarantees a current frame. */\n\t\tif (frame === void 0) break;\n\t\ttry {\n\t\t\tif (frame.phase === \"children\") {\n\t\t\t\tif (frame.childIndex < frame.children.length) {\n\t\t\t\t\tconst child = frame.children[frame.childIndex];\n\t\t\t\t\t/* v8 ignore next -- childIndex is bounded by children.length. */\n\t\t\t\t\tif (child === void 0) throw new Error(\"missing schema-value child frame\");\n\t\t\t\t\tframe.childIndex++;\n\t\t\t\t\tframes.push(valueFrame(child.node, child.value, child.path));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (frame.kind === \"oneOf\") {\n\t\t\t\t\tfinish(frame.matches === 1 ? [] : [`\"${diagnosticPath(frame.path)}\" must match exactly one oneOf branch (matched ${frame.matches})`]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tappendViolations(frame.violations, frame.tailViolations);\n\t\t\t\tif (frame.violations.length > 0) finish(frame.violations);\n\t\t\t\telse if (frame.kind === \"object\") finish(safelyIsJsonValue(frame.value) ? [] : [`\"${diagnosticPath(frame.path)}\" must be a lossless JSON object`]);\n\t\t\t\telse finish(safelyIsJsonValue(frame.value) ? [] : [`\"${diagnosticPath(frame.path)}\" must be a dense lossless JSON array`]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst nodeType = Object.hasOwn(frame.node, \"type\") ? frame.node.type : void 0;\n\t\t\tframe.catches = !(nodeType !== void 0 && !SCHEMA_TYPES.includes(nodeType));\n\t\t\tconst oneOf = Object.hasOwn(frame.node, \"oneOf\") ? frame.node.oneOf : void 0;\n\t\t\tif (oneOf !== void 0) {\n\t\t\t\tframe.kind = \"oneOf\";\n\t\t\t\tframe.children = Array.from(oneOf, (branch) => ({\n\t\t\t\t\tnode: branch,\n\t\t\t\t\tvalue: frame.value,\n\t\t\t\t\tpath: frame.path\n\t\t\t\t}));\n\t\t\t\tframe.childIndex = 0;\n\t\t\t\tframe.matches = 0;\n\t\t\t\tframe.phase = \"children\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (nodeType === void 0) {\n\t\t\t\tfinish(safelyIsJsonValue(frame.value) ? [] : losslessValueViolation(frame.path));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tswitch (nodeType) {\n\t\t\t\tcase \"object\": {\n\t\t\t\t\tif (!isPlainJsonRecord(frame.value)) {\n\t\t\t\t\t\tfinish([`\"${diagnosticPath(frame.path)}\" must be an object`]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst properties = Object.hasOwn(frame.node, \"properties\") ? frame.node.properties ?? {} : {};\n\t\t\t\t\tconst violations = [];\n\t\t\t\t\tconst required = Object.hasOwn(frame.node, \"required\") ? frame.node.required ?? [] : [];\n\t\t\t\t\tfor (const key of required) if (!Object.hasOwn(frame.value, key) || frame.value[key] === void 0) violations.push(`missing required property \"${propertyPath(frame.path, key)}\"`);\n\t\t\t\t\tconst children = [];\n\t\t\t\t\tfor (const [key, child] of Object.entries(properties)) {\n\t\t\t\t\t\tif (!Object.hasOwn(frame.value, key) || frame.value[key] === void 0) continue;\n\t\t\t\t\t\tchildren.push({\n\t\t\t\t\t\t\tnode: child,\n\t\t\t\t\t\t\tvalue: frame.value[key],\n\t\t\t\t\t\t\tpath: propertyPath(frame.path, key)\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tconst tailViolations = [];\n\t\t\t\t\tif (Object.hasOwn(frame.node, \"additionalProperties\") && frame.node.additionalProperties === false) {\n\t\t\t\t\t\tfor (const key of Object.keys(frame.value)) if (!Object.hasOwn(properties, key)) tailViolations.push(`\"${propertyPath(frame.path, key)}\" is not a declared property (additionalProperties: false)`);\n\t\t\t\t\t}\n\t\t\t\t\tframe.kind = \"object\";\n\t\t\t\t\tframe.children = children;\n\t\t\t\t\tframe.childIndex = 0;\n\t\t\t\t\tframe.violations = violations;\n\t\t\t\t\tframe.tailViolations = tailViolations;\n\t\t\t\t\tframe.phase = \"children\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"array\": {\n\t\t\t\t\tif (!Array.isArray(frame.value)) {\n\t\t\t\t\t\tfinish([`\"${diagnosticPath(frame.path)}\" must be an array`]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst items = Object.hasOwn(frame.node, \"items\") ? frame.node.items : void 0;\n\t\t\t\t\tconst children = items === void 0 ? [] : frame.value.flatMap((entry, index) => [{\n\t\t\t\t\t\tnode: items,\n\t\t\t\t\t\tvalue: entry,\n\t\t\t\t\t\tpath: `${frame.path}[${index}]`\n\t\t\t\t\t}]);\n\t\t\t\t\tframe.kind = \"array\";\n\t\t\t\t\tframe.children = children;\n\t\t\t\t\tframe.childIndex = 0;\n\t\t\t\t\tframe.violations = [];\n\t\t\t\t\tframe.phase = \"children\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"string\":\n\t\t\t\t\tfinish(typeof frame.value === \"string\" ? checkScalarValue(frame.node, frame.value, frame.path) : [`\"${diagnosticPath(frame.path)}\" must be a string`]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"number\":\n\t\t\t\t\tfinish(typeof frame.value !== \"number\" ? [`\"${diagnosticPath(frame.path)}\" must be a number`] : !isJsonNumber(frame.value) ? [`\"${diagnosticPath(frame.path)}\" must be a finite JSON number`] : checkScalarValue(frame.node, frame.value, frame.path));\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"integer\":\n\t\t\t\t\tfinish(!isJsonNumber(frame.value) || !Number.isInteger(frame.value) ? [`\"${diagnosticPath(frame.path)}\" must be an integer`] : checkScalarValue(frame.node, frame.value, frame.path));\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"boolean\":\n\t\t\t\t\tfinish(typeof frame.value === \"boolean\" ? checkScalarValue(frame.node, frame.value, frame.path) : [`\"${diagnosticPath(frame.path)}\" must be a boolean`]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"null\":\n\t\t\t\t\tfinish(frame.value === null ? checkScalarValue(frame.node, frame.value, frame.path) : [`\"${diagnosticPath(frame.path)}\" must be null`]);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: finish(assertNever(nodeType, \"JsonSchemaType\"));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlet failed = frames.pop();\n\t\t\twhile (failed !== void 0 && !failed.catches) failed = frames.pop();\n\t\t\tif (failed === void 0) throw error;\n\t\t\treceive(losslessValueViolation(failed.path));\n\t\t}\n\t}\n\t/* v8 ignore next -- every root frame finishes or throws. */\n\treturn rootResult ?? losslessValueViolation(path);\n}\n/**\n* Validate a candidate value against an asserted raw schema. The function is\n* total for arbitrary values and returns path-qualified violations.\n* @param schema - a schema accepted by {@link assertSupportedJsonSchema}.\n* @param value - the candidate JSON value.\n* @param path - root label used in diagnostics.\n* @returns All violations in walk order; empty means valid.\n*/\nfunction validateJsonSchemaValue(schema, value, path = \"value\") {\n\treturn checkValue(schema, value, path);\n}\n//#endregion\n//#region lib/types/schema.js\n/** Unified JSON-value schema DSL, inference, compilation, and typed tool helper. @module dsh-tools/schema */\nconst ANNOTATION_KEYS = [\n\t\"description\",\n\t\"title\",\n\t\"default\",\n\t\"examples\"\n];\n/** Throw one author-schema violation through the shared schema error type. */\nfunction authorError(message) {\n\tthrow new JsonSchemaError([message]);\n}\n/** Copy own annotation fields for validation by the raw-schema boundary. */\nfunction copyAnnotations(source, target) {\n\tif (Object.hasOwn(source, \"description\")) target.description = source.description;\n\tif (Object.hasOwn(source, \"title\")) target.title = source.title;\n\tif (Object.hasOwn(source, \"default\")) target.default = source.default;\n\tif (Object.hasOwn(source, \"examples\")) target.examples = source.examples;\n}\n/** Reject author-only keys outside one node's declared vocabulary. */\nfunction assertAuthorKeys(source, path, allowed) {\n\tfor (const key of Object.keys(source)) if (!allowed.includes(key)) authorError(`${path}.${key} is not supported by the value schema DSL`);\n}\n/** Install a compiled node without giving `__proto__` assignment semantics. */\nfunction assignCompiledNode(destination, node) {\n\tswitch (destination.kind) {\n\t\tcase \"root\":\n\t\t\tdestination.holder.value = node;\n\t\t\tbreak;\n\t\tcase \"property\":\n\t\t\tObject.defineProperty(destination.target, destination.key, {\n\t\t\t\tvalue: node,\n\t\t\t\tenumerable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"item\":\n\t\t\tdestination.target.items = node;\n\t\t\tbreak;\n\t\tcase \"one-of\":\n\t\t\tdestination.target[destination.index] = node;\n\t\t\tbreak;\n\t}\n}\n/** Install a compiled property map at its root or containing object node. */\nfunction assignCompiledPropertyMap(destination, compiled) {\n\tif (destination.kind === \"root\") destination.holder.value = compiled;\n\telse destination.target.properties = compiled.properties;\n}\n/** Execute an author-schema compilation task graph without recursive descent. */\nfunction runSchemaCompiler(initial) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst tasks = [initial];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (task.kind === \"leave\") {\n\t\t\tseen.delete(task.input);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"property-map-tail\") {\n\t\t\tif (task.required.length > 0) {\n\t\t\t\ttask.compiled.required = task.required;\n\t\t\t\tif (task.destination.kind === \"object\") task.destination.target.required = task.required;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"property\") {\n\t\t\tif (!isJsonSchemaRecord(task.property)) authorError(`${task.path} must be a value schema object`);\n\t\t\tif (Object.hasOwn(task.property, \"required\") && task.property.required !== true) authorError(`${task.path}.required must be true when present`);\n\t\t\tif (Object.hasOwn(task.property, \"required\") && task.property.required === true) task.required.push(task.key);\n\t\t\ttasks.push({\n\t\t\t\tkind: \"value\",\n\t\t\t\tinput: task.property,\n\t\t\t\tpath: task.path,\n\t\t\t\tallowRequired: true,\n\t\t\t\tdestination: {\n\t\t\t\t\tkind: \"property\",\n\t\t\t\t\ttarget: task.properties,\n\t\t\t\t\tkey: task.key\n\t\t\t\t}\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"property-map\") {\n\t\t\tif (!isJsonSchemaRecord(task.input)) authorError(`${task.path} must be an object of value schemas`);\n\t\t\tif (seen.has(task.input)) authorError(`${task.path} is circular`);\n\t\t\tseen.add(task.input);\n\t\t\tconst compiled = { properties: {} };\n\t\t\tconst required = [];\n\t\t\tassignCompiledPropertyMap(task.destination, compiled);\n\t\t\ttasks.push({\n\t\t\t\tkind: \"leave\",\n\t\t\t\tinput: task.input\n\t\t\t});\n\t\t\ttasks.push({\n\t\t\t\tkind: \"property-map-tail\",\n\t\t\t\tcompiled,\n\t\t\t\trequired,\n\t\t\t\tdestination: task.destination\n\t\t\t});\n\t\t\tconst entries = Object.entries(task.input);\n\t\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\t\tconst entry = entries[index];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured entry count. */\n\t\t\t\tif (entry === void 0) continue;\n\t\t\t\ttasks.push({\n\t\t\t\t\tkind: \"property\",\n\t\t\t\t\tproperty: entry[1],\n\t\t\t\t\tpath: `${task.path}.${entry[0]}`,\n\t\t\t\t\tkey: entry[0],\n\t\t\t\t\tproperties: compiled.properties,\n\t\t\t\t\trequired\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst { input, path } = task;\n\t\tif (!isJsonSchemaRecord(input)) authorError(`${path} must be a value schema object`);\n\t\tif (seen.has(input)) authorError(`${path} is circular`);\n\t\tseen.add(input);\n\t\tconst authorKeys = [...ANNOTATION_KEYS, ...task.allowRequired ? [\"required\"] : []];\n\t\tconst node = {};\n\t\tassignCompiledNode(task.destination, node);\n\t\ttasks.push({\n\t\t\tkind: \"leave\",\n\t\t\tinput\n\t\t});\n\t\tif (Object.hasOwn(input, \"oneOf\")) {\n\t\t\tassertAuthorKeys(input, path, [\n\t\t\t\t...authorKeys,\n\t\t\t\t\"oneOf\",\n\t\t\t\t\"type\"\n\t\t\t]);\n\t\t\tif (Object.hasOwn(input, \"type\")) authorError(`${path} cannot declare both type and oneOf`);\n\t\t\tif (!isPlainJsonArray(input.oneOf)) authorError(`${path}.oneOf must be an array of at least two value schemas`);\n\t\t\tconst branches = [];\n\t\t\tnode.oneOf = branches;\n\t\t\tcopyAnnotations(input, node);\n\t\t\tfor (let index = input.oneOf.length - 1; index >= 0; index--) tasks.push({\n\t\t\t\tkind: \"value\",\n\t\t\t\tinput: input.oneOf[index],\n\t\t\t\tpath: `${path}.oneOf[${index}]`,\n\t\t\t\tallowRequired: false,\n\t\t\t\tdestination: {\n\t\t\t\t\tkind: \"one-of\",\n\t\t\t\t\ttarget: branches,\n\t\t\t\t\tindex\n\t\t\t\t}\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst inputType = Object.hasOwn(input, \"type\") ? input.type : void 0;\n\t\tswitch (inputType) {\n\t\t\tcase \"json\":\n\t\t\t\tassertAuthorKeys(input, path, [...authorKeys, \"type\"]);\n\t\t\t\tcopyAnnotations(input, node);\n\t\t\t\tbreak;\n\t\t\tcase \"object\":\n\t\t\t\tassertAuthorKeys(input, path, [\n\t\t\t\t\t...authorKeys,\n\t\t\t\t\t\"type\",\n\t\t\t\t\t\"properties\",\n\t\t\t\t\t\"additionalProperties\"\n\t\t\t\t]);\n\t\t\t\tif (!Object.hasOwn(input, \"additionalProperties\") || typeof input.additionalProperties !== \"boolean\") authorError(`${path}.additionalProperties must be explicitly true or false`);\n\t\t\t\tnode.type = \"object\";\n\t\t\t\tcopyAnnotations(input, node);\n\t\t\t\tnode.additionalProperties = input.additionalProperties;\n\t\t\t\tif (Object.hasOwn(input, \"properties\")) tasks.push({\n\t\t\t\t\tkind: \"property-map\",\n\t\t\t\t\tinput: input.properties,\n\t\t\t\t\tpath: `${path}.properties`,\n\t\t\t\t\tdestination: {\n\t\t\t\t\t\tkind: \"object\",\n\t\t\t\t\t\ttarget: node\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"array\":\n\t\t\t\tassertAuthorKeys(input, path, [\n\t\t\t\t\t...authorKeys,\n\t\t\t\t\t\"type\",\n\t\t\t\t\t\"items\"\n\t\t\t\t]);\n\t\t\t\tnode.type = \"array\";\n\t\t\t\tcopyAnnotations(input, node);\n\t\t\t\tif (Object.hasOwn(input, \"items\")) tasks.push({\n\t\t\t\t\tkind: \"value\",\n\t\t\t\t\tinput: input.items,\n\t\t\t\t\tpath: `${path}.items`,\n\t\t\t\t\tallowRequired: false,\n\t\t\t\t\tdestination: {\n\t\t\t\t\t\tkind: \"item\",\n\t\t\t\t\t\ttarget: node\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"string\":\n\t\t\tcase \"number\":\n\t\t\tcase \"integer\":\n\t\t\tcase \"boolean\":\n\t\t\tcase \"null\":\n\t\t\t\tassertAuthorKeys(input, path, [\n\t\t\t\t\t...authorKeys,\n\t\t\t\t\t\"type\",\n\t\t\t\t\t\"enum\",\n\t\t\t\t\t\"const\"\n\t\t\t\t]);\n\t\t\t\tnode.type = inputType;\n\t\t\t\tcopyAnnotations(input, node);\n\t\t\t\tif (Object.hasOwn(input, \"enum\")) {\n\t\t\t\t\tif (!isPlainJsonArray(input.enum)) authorError(`${path}.enum must be a non-empty array of scalar values`);\n\t\t\t\t\tnode.enum = Array.from(input.enum, (entry) => entry);\n\t\t\t\t}\n\t\t\t\tif (Object.hasOwn(input, \"const\")) node.const = input.const;\n\t\t\t\tbreak;\n\t\t\tdefault: authorError(`${path}.type must be string/number/integer/boolean/null/array/object/json, or use oneOf`);\n\t\t}\n\t}\n}\n/** Compile one implicit property map, collecting per-property requiredness. */\nfunction compilePropertyMap(input, path) {\n\tconst holder = {};\n\trunSchemaCompiler({\n\t\tkind: \"property-map\",\n\t\tinput,\n\t\tpath,\n\t\tdestination: {\n\t\t\tkind: \"root\",\n\t\t\tholder\n\t\t}\n\t});\n\t/* v8 ignore next -- the root task assigns before scheduling any descendants. */\n\treturn holder.value ?? authorError(`${path} did not compile`);\n}\n/** Compile one author node without applying any consumer root restriction. */\nfunction compileValueSchema(input, path) {\n\tconst holder = {};\n\trunSchemaCompiler({\n\t\tkind: \"value\",\n\t\tinput,\n\t\tpath,\n\t\tallowRequired: false,\n\t\tdestination: {\n\t\t\tkind: \"root\",\n\t\t\tholder\n\t\t}\n\t});\n\t/* v8 ignore next -- the root task assigns before scheduling any descendants. */\n\treturn holder.value ?? authorError(`${path} did not compile`);\n}\n/**\n* Compile one author-facing value schema to the enforced raw JSON Schema\n* subset. The author-only `json` node becomes an annotation-only schema.\n* @param spec - schema for any JSON-value root.\n* @returns The asserted raw schema projection.\n*/\nfunction valueSchemaSpecToJsonSchema(spec) {\n\tconst schema = compileValueSchema(spec, \"schema\");\n\tassertSupportedJsonSchema(schema);\n\treturn schema;\n}\n/**\n* Compile the implicit open parameter object into raw JSON Schema.\n* @param spec - per-property parameter definitions.\n* @returns An object-rooted raw schema with no implicit-root openness override.\n*/\nfunction parameterSchemaSpecToJsonSchema(spec) {\n\tconst compiled = compilePropertyMap(spec, \"parameters\");\n\tconst schema = {\n\t\ttype: \"object\",\n\t\tproperties: compiled.properties,\n\t\t...compiled.required === void 0 ? {} : { required: compiled.required }\n\t};\n\tassertSupportedJsonSchema(schema);\n\treturn schema;\n}\n/** Invalid model-generated arguments for a typed tool. */\nvar ToolArgsError = class extends HarnessError {\n\t/** Individual violations in schema-walk order. */\n\tviolations;\n\tconstructor(violations) {\n\t\tsuper(`invalid arguments: ${violations.join(\"; \")}`, \"INVALID_ARGS\");\n\t\tthis.name = \"ToolArgsError\";\n\t\tthis.violations = violations;\n\t}\n};\n/**\n* Validate model-generated arguments against an implicit parameter schema.\n* @param spec - declared parameter schema.\n* @param args - candidate arguments, however malformed.\n* @returns Path-qualified violations; empty means valid.\n*/\nfunction validateArgs(spec, args) {\n\treturn validateJsonSchemaValue(parameterSchemaSpecToJsonSchema(spec), args, \"\");\n}\n/**\n* Define a first-party tool with inferred arguments and strict execution\n* validation. Replay-only presenters validate softly and fall back to generic\n* rendering for obsolete logged arguments.\n* @param options - typed definition and optional finalizer and presenters.\n* @returns A registry-ready definition.\n*/\nfunction defineTool(options) {\n\tconst userExecute = options.execute;\n\tconst userFinalizeContent = options.finalizeContent;\n\tconst userRender = options.output.render;\n\tconst userPresentationMeta = options.output.presentationMeta;\n\tconst userPresentCall = options.presentCall;\n\tconst userPresentResult = options.presentResult;\n\tconst userIsConcurrencySafe = options.isConcurrencySafe;\n\tif (options.timeoutMs !== void 0 && (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0)) throw new Error(`defineTool(${options.name}): timeoutMs must be a positive finite number`);\n\tconst parameters = parameterSchemaSpecToJsonSchema(options.parameters);\n\tconst outputSchema = valueSchemaSpecToJsonSchema(options.output.schema);\n\tconst validate = (args) => validateJsonSchemaValue(parameters, args, \"\");\n\tconst tool = {\n\t\tname: options.name,\n\t\tdescription: options.description,\n\t\tparameters,\n\t\toutput: {\n\t\t\tschema: outputSchema,\n\t\t\trender(args, value) {\n\t\t\t\treturn userRender(args, value);\n\t\t\t},\n\t\t\t...userPresentationMeta !== void 0 ? { presentationMeta(args, value) {\n\t\t\t\treturn userPresentationMeta(args, value);\n\t\t\t} } : {}\n\t\t},\n\t\t...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},\n\t\tasync execute(args, exec) {\n\t\t\tconst violations = validate(args);\n\t\t\tif (violations.length > 0) throw new ToolArgsError(violations);\n\t\t\treturn userExecute(args, exec);\n\t\t}\n\t};\n\tif (userFinalizeContent) tool.finalizeContent = (exec, result) => userFinalizeContent(exec, result);\n\tif (userPresentCall) tool.presentCall = (args) => {\n\t\tif (validate(args).length > 0) return void 0;\n\t\treturn userPresentCall(args);\n\t};\n\tif (userPresentResult) tool.presentResult = (args, result) => {\n\t\tif (validate(args).length > 0) return void 0;\n\t\treturn userPresentResult(args, result);\n\t};\n\tif (userIsConcurrencySafe) tool.isConcurrencySafe = (args) => {\n\t\tif (validate(args).length > 0) return false;\n\t\treturn userIsConcurrencySafe(args);\n\t};\n\treturn tool;\n}\n//#endregion\n//#region lib/types/code-mode.js\n/**\n* Code Mode `run_code` transport. Programs call the registry's agent-visible\n* tools through nested executions scheduled under the native concurrency\n* contract; each sub-dispatch is logged for reconstruction, while only the\n* outer curated result enters model history.\n* @module @deepseek-ai/dsh-tools/src/code-mode\n*/\n/** The model-facing name of the Code Mode tool. */\nconst RUN_CODE_NAME = \"run_code\";\n/**\n* The TypeScript flavor: the fallback for a schema read with no runtime\n* mounted ({@link resolveFlavor} owns which readers reach that). A real\n* assembly always resolves a runtime first, so the model never sees this\n* fallback outside its own language.\n*/\nconst TYPESCRIPT_FLAVOR = {\n\tdescription: \"Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return comes back — curate it.\",\n\tcodeDescription: \"The program: the body of an async TypeScript function.\"\n};\n/** Per-language `run_code` schema flavors (see {@link RunCodeFlavor}); one entry per {@link CodeSdkLanguage}. */\nconst RUN_CODE_FLAVORS = {\n\ttypescript: TYPESCRIPT_FLAVOR,\n\tpython: {\n\t\tdescription: \"Execute a Python program against the available tools. Takes two required arguments: `code`, the BODY of an async function (top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Answer with `print(...)` and/or `return <value>` — only that comes back, so curate it.\",\n\t\tcodeDescription: \"The program: the body of an async Python function.\"\n\t}\n};\n/**\n* The `description` parameter's model-facing description: language-independent\n* (the UI label contract is the same for every runtime), shared between the\n* static spec and the language-aware `parameters` getter so the two emissions\n* can never drift.\n*/\nconst RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION = \"Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI). Examples: \\\"Count TODO markers across packages\\\"; \\\"Read failing test and its fixture\\\"; \\\"Rename config key in every cordis.yml\\\".\";\n/**\n* Resolve the {@link RunCodeFlavor} for the loaded runtime's language, read at\n* schema-emission time so the model-visible `run_code` schema always matches\n* the SDK section's language. `peekRuntime` returns `undefined` only when no\n* runtime is mounted, which reaches this function through definition readers\n* and `schemas()` — the doc-catalog harvest is the only shipped one, and none\n* of them feeds a model, because `wireSchemas` calls `requireCodeRuntime`\n* before projecting — so that path degrades to {@link TYPESCRIPT_FLAVOR}. A\n* mounted runtime whose language has no flavor entry fails loud, exactly as\n* `requireCodeRuntime` rejects it at assembly. Keeping this table in step with\n* `SDK_RENDERERS` is the compiler's job ({@link CodeSdkLanguage}); what this\n* guard owns is the runtime-supplied language neither table knows, which never\n* yields a wrong-language schema for a real runtime.\n*/\nfunction resolveFlavor(peekRuntime) {\n\tconst runtime = peekRuntime();\n\tif (runtime === void 0) return TYPESCRIPT_FLAVOR;\n\tconst flavor = RUN_CODE_FLAVORS[runtime.language];\n\tif (!Object.hasOwn(RUN_CODE_FLAVORS, runtime.language) || flavor === void 0) {\n\t\tconst known = Object.keys(RUN_CODE_FLAVORS).map((name) => JSON.stringify(name)).join(\", \");\n\t\tthrow new Error(`dsh-tools: no run_code schema flavor registered for runtime language ${JSON.stringify(runtime.language)} (known: ${known})`);\n\t}\n\treturn flavor;\n}\n/**\n* Thrown by `run_code` when the program run itself failed — a program\n* exception, a budget expiry, an abort, or substrate death. Extends\n* {@link HarnessError} (`code: 'CODE_RUN_FAILED'`); the registry's execution\n* pipeline converts it into a structured `isError` result whose text carries\n* the failure kind plus the captured logs, so the model can self-correct.\n*/\nvar CodeRunFailedError = class extends HarnessError {\n\tconstructor(message) {\n\t\tsuper(message, \"CODE_RUN_FAILED\");\n\t\tthis.name = \"CodeRunFailedError\";\n\t}\n};\n/**\n* Snapshot one binding call's argument as lossless JSON, then snapshot that\n* detached value again so dispatch and logging stay independent without\n* reintroducing structured-clone's platform-specific nesting limit.\n*/\nfunction jsonNormalizeArgs(value) {\n\tlet snapshot;\n\ttry {\n\t\tsnapshot = snapshotJsonValue(value);\n\t} catch (error) {\n\t\tthrow new Error(`tool arguments must be lossless JSON: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n\tif (snapshot === void 0) throw new Error(\"tool arguments must be lossless JSON (call the tool with an arguments object, e.g. `{}`)\");\n\tconst logged = snapshotJsonValue(snapshot);\n\t/* v8 ignore next -- snapshot is already a detached lossless JSON value. */\n\tif (logged === void 0) throw new Error(\"tool arguments could not be detached for durable logging\");\n\treturn {\n\t\tdispatched: snapshot,\n\t\tlogged\n\t};\n}\n/** Two-space JSON presentation, matching the existing shallow `run_code` text contract. */\nconst JSON_INDENT = \" \";\n/**\n* ECMAScript caps `JSON.stringify`'s `space` string at ten characters. The\n* renderer also caps TOTAL indentation there, compacting deeper subtrees, so\n* formatted output remains linear in the canonical JSON size.\n*/\nconst MAX_JSON_INDENT_CHARS = 10;\n/** Render one non-string JSON root without recursive traversal or unbounded indentation growth. */\nfunction renderJsonValue(value) {\n\tconst chunks = [];\n\tconst tasks = [{\n\t\tkind: \"value\",\n\t\tvalue,\n\t\tdepth: 0,\n\t\tcompact: false\n\t}];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (task.kind === \"text\") {\n\t\t\tchunks.push(task.text);\n\t\t\tcontinue;\n\t\t}\n\t\tconst current = task.value;\n\t\tif (current === null || typeof current === \"boolean\" || typeof current === \"number\") {\n\t\t\tchunks.push(String(current));\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof current === \"string\") {\n\t\t\tchunks.push(JSON.stringify(current));\n\t\t\tcontinue;\n\t\t}\n\t\tconst compact = task.compact || (task.depth + 1) * 2 > MAX_JSON_INDENT_CHARS;\n\t\tconst childDepth = task.depth + 1;\n\t\tif (Array.isArray(current)) {\n\t\t\tchunks.push(\"[\");\n\t\t\tif (current.length === 0) {\n\t\t\t\tchunks.push(\"]\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttasks.push({\n\t\t\t\tkind: \"text\",\n\t\t\t\ttext: compact ? \"]\" : `\\n${JSON_INDENT.repeat(task.depth)}]`\n\t\t\t});\n\t\t\tfor (let index = current.length - 1; index >= 0; index--) {\n\t\t\t\tconst item = current[index];\n\t\t\t\t/* v8 ignore next -- canonical JsonValue arrays are dense. */\n\t\t\t\tif (item === void 0) throw new Error(\"cannot render a sparse JSON array\");\n\t\t\t\ttasks.push({\n\t\t\t\t\tkind: \"value\",\n\t\t\t\t\tvalue: item,\n\t\t\t\t\tdepth: childDepth,\n\t\t\t\t\tcompact\n\t\t\t\t});\n\t\t\t\ttasks.push({\n\t\t\t\t\tkind: \"text\",\n\t\t\t\t\ttext: compact ? index === 0 ? \"\" : \",\" : `${index === 0 ? \"\\n\" : \",\\n\"}${JSON_INDENT.repeat(childDepth)}`\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst keys = Object.keys(current);\n\t\tchunks.push(\"{\");\n\t\tif (keys.length === 0) {\n\t\t\tchunks.push(\"}\");\n\t\t\tcontinue;\n\t\t}\n\t\ttasks.push({\n\t\t\tkind: \"text\",\n\t\t\ttext: compact ? \"}\" : `\\n${JSON_INDENT.repeat(task.depth)}}`\n\t\t});\n\t\tfor (let index = keys.length - 1; index >= 0; index--) {\n\t\t\tconst key = keys[index];\n\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\tif (key === void 0) throw new Error(\"cannot render a missing JSON object key\");\n\t\t\tconst item = current[key];\n\t\t\t/* v8 ignore next -- canonical JsonValue records contain no undefined properties. */\n\t\t\tif (item === void 0) throw new Error(\"cannot render an undefined JSON object property\");\n\t\t\ttasks.push({\n\t\t\t\tkind: \"value\",\n\t\t\t\tvalue: item,\n\t\t\t\tdepth: childDepth,\n\t\t\t\tcompact\n\t\t\t});\n\t\t\ttasks.push({\n\t\t\t\tkind: \"text\",\n\t\t\t\ttext: compact ? `${index === 0 ? \"\" : \",\"}${JSON.stringify(key)}:` : `${index === 0 ? \"\\n\" : \",\\n\"}${JSON_INDENT.repeat(childDepth)}${JSON.stringify(key)}: `\n\t\t\t});\n\t\t}\n\t}\n\treturn chunks.join(\"\");\n}\n/** Render one present program completion value for the model-facing result text. */\nfunction renderValue(value) {\n\treturn typeof value === \"string\" ? value : renderJsonValue(value);\n}\n/**\n* Build the `run_code` {@link ToolDefinition}: required `code` and\n* `description` parameters, executed through the dispatch bridge described\n* above. The\n* registry reserves it as presentation infrastructure under non-native modes,\n* outside the filterable global/scoped capability layers.\n* @param registry - the owning registry (sub-calls go through its `execute`,\n* bindings cover its registered tools).\n* @param options - the registry-private capabilities described above.\n* @returns the registry-ready definition.\n*/\nfunction createRunCodeTool(registry, options) {\n\tconst { requireRuntime, peekRuntime, maxParallel, shapeDispatchLog } = options;\n\tconst definition = defineTool({\n\t\tname: RUN_CODE_NAME,\n\t\tdescription: TYPESCRIPT_FLAVOR.description,\n\t\tparameters: {\n\t\t\tcode: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\tdescription: TYPESCRIPT_FLAVOR.codeDescription\n\t\t\t},\n\t\t\tdescription: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\tdescription: RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION\n\t\t\t}\n\t\t},\n\t\toutput: {\n\t\t\tschema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tadditionalProperties: false,\n\t\t\t\tproperties: {\n\t\t\t\t\tlogs: {\n\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\trequired: true,\n\t\t\t\t\t\titems: { type: \"string\" }\n\t\t\t\t\t},\n\t\t\t\t\tresult: { type: \"json\" }\n\t\t\t\t}\n\t\t\t},\n\t\t\trender: (_args, value) => {\n\t\t\t\tconst rendered = value.result === void 0 ? \"\" : renderValue(value.result);\n\t\t\t\tconst parts = [value.logs.join(\"\\n\"), rendered].filter((part) => part.length > 0);\n\t\t\t\treturn [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: parts.length > 0 ? parts.join(\"\\n\") : \"(run_code completed with no output)\"\n\t\t\t\t}];\n\t\t\t}\n\t\t},\n\t\tasync execute(args, exec) {\n\t\t\tif (args.description.trim().length === 0) throw new Error(\"invalid description: expected a non-empty string\");\n\t\t\tconst runtime = requireRuntime();\n\t\t\tconst runController = new AbortController();\n\t\t\tconst onOuterAbort = () => {\n\t\t\t\trunController.abort(exec.signal.reason);\n\t\t\t};\n\t\t\texec.signal.addEventListener(\"abort\", onOuterAbort, { once: true });\n\t\t\tlet dispatches = 0;\n\t\t\tconst pendingQueue = [];\n\t\t\tconst inFlight = /* @__PURE__ */ new Set();\n\t\t\t/** Tracked settle-event side work (log-content listener + append), drained at run settlement. */\n\t\t\tconst logWork = /* @__PURE__ */ new Set();\n\t\t\tconst commitQueue = [];\n\t\t\tlet exclusiveActive = false;\n\t\t\tlet driving = false;\n\t\t\tlet driverRun = Promise.resolve();\n\t\t\tlet wake;\n\t\t\tconst wakeup = () => {\n\t\t\t\tconst release = wake;\n\t\t\t\twake = void 0;\n\t\t\t\trelease?.();\n\t\t\t};\n\t\t\t/**\n\t\t\t* The single ordered lane. Each pass commits the head-of-line settled\n\t\t\t* dispatch (ordered post-execute), then starts the next queued entry if\n\t\t\t* its slot is free (ordered pre-execute), and otherwise sleeps until a\n\t\t\t* body settles or a new submission arrives. One run reaching the\n\t\t\t* empty-queues/empty-pool state is quiescence.\n\t\t\t*/\n\t\t\tconst drive = () => {\n\t\t\t\tif (driving) return driverRun;\n\t\t\t\tdriving = true;\n\t\t\t\tdriverRun = (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\t\tconst signal = new Promise((resolve) => {\n\t\t\t\t\t\t\t\twake = resolve;\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst commitHead = commitQueue[0];\n\t\t\t\t\t\t\tif (commitHead !== void 0 && commitHead.settled) {\n\t\t\t\t\t\t\t\tcommitQueue.shift();\n\t\t\t\t\t\t\t\tawait commitHead.commit();\n\t\t\t\t\t\t\t\tif (commitHead.mode === \"exclusive\") exclusiveActive = false;\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst head = pendingQueue[0];\n\t\t\t\t\t\t\tif (head !== void 0) {\n\t\t\t\t\t\t\t\tif (runController.signal.aborted) {\n\t\t\t\t\t\t\t\t\tpendingQueue.shift();\n\t\t\t\t\t\t\t\t\thead.abandon();\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst mode = head.classify();\n\t\t\t\t\t\t\t\tif (!exclusiveActive && (mode === \"exclusive\" ? inFlight.size === 0 : inFlight.size < maxParallel)) {\n\t\t\t\t\t\t\t\t\tif (mode === \"exclusive\") exclusiveActive = true;\n\t\t\t\t\t\t\t\t\thead.mode = mode;\n\t\t\t\t\t\t\t\t\tpendingQueue.shift();\n\t\t\t\t\t\t\t\t\tcommitQueue.push(head);\n\t\t\t\t\t\t\t\t\tawait head.start();\n\t\t\t\t\t\t\t\t\tconst flight = head.flight.finally(() => {\n\t\t\t\t\t\t\t\t\t\tinFlight.delete(flight);\n\t\t\t\t\t\t\t\t\t\twakeup();\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tinFlight.add(flight);\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (pendingQueue.length === 0 && commitQueue.length === 0 && inFlight.size === 0) return;\n\t\t\t\t\t\t\tawait signal;\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tdriving = false;\n\t\t\t\t\t\twake = void 0;\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\treturn driverRun;\n\t\t\t};\n\t\t\t/** Every dispatch settled AND committed; nothing can start (the run is aborted at call time). */\n\t\t\tconst drainDispatches = async () => {\n\t\t\t\tawait drive();\n\t\t\t\twhile (logWork.size > 0) await Promise.allSettled([...logWork]);\n\t\t\t};\n\t\t\tconst runOver = () => runController.signal.aborted;\n\t\t\tconst binding = (name) => async (rawArgs) => {\n\t\t\t\tif (runOver()) throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} not dispatched`);\n\t\t\t\tconst normalized = jsonNormalizeArgs(rawArgs);\n\t\t\t\tconst n = ++dispatches;\n\t\t\t\tconst subCallId = CallId(`${String(exec.callId)}:code:${n}`);\n\t\t\t\tconst input = {\n\t\t\t\t\tcallId: subCallId,\n\t\t\t\t\trootCallId: exec.rootCallId,\n\t\t\t\t\tname,\n\t\t\t\t\targuments: normalized.dispatched,\n\t\t\t\t\t...exec.agent ? { agent: exec.agent } : {},\n\t\t\t\t\tparent: exec.token,\n\t\t\t\t\tsignal: runController.signal\n\t\t\t\t};\n\t\t\t\tconst scheduler = registry[TOOL_RUNTIME_SCHEDULER];\n\t\t\t\tconst outcome = await new Promise((resolve, reject) => {\n\t\t\t\t\tlet parked;\n\t\t\t\t\tconst settle = (result) => {\n\t\t\t\t\t\tresolve(result.isError ? {\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\tmessage: result.error.message\n\t\t\t\t\t\t} : {\n\t\t\t\t\t\t\tisError: false,\n\t\t\t\t\t\t\tvalue: result.value\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst agent = exec.agent;\n\t\t\t\t\t\tif (agent === void 0) return;\n\t\t\t\t\t\tconst task = (async () => {\n\t\t\t\t\t\t\tconst logged = await shapeDispatchLog({\n\t\t\t\t\t\t\t\texec,\n\t\t\t\t\t\t\t\tagent,\n\t\t\t\t\t\t\t\tsubCallId,\n\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\tisError: result.isError,\n\t\t\t\t\t\t\t\tcontent: result.content\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tagent.session.append(\"tool/code-dispatch\", {\n\t\t\t\t\t\t\t\trootCallId: exec.rootCallId,\n\t\t\t\t\t\t\t\tparentCallId: exec.callId,\n\t\t\t\t\t\t\t\tsubCallId,\n\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\targuments: normalized.logged,\n\t\t\t\t\t\t\t\tisError: result.isError,\n\t\t\t\t\t\t\t\tcontent: logged\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t})().finally(() => {\n\t\t\t\t\t\t\tlogWork.delete(task);\n\t\t\t\t\t\t});\n\t\t\t\t\t\tlogWork.add(task);\n\t\t\t\t\t};\n\t\t\t\t\tpendingQueue.push({\n\t\t\t\t\t\tflight: Promise.resolve(),\n\t\t\t\t\t\tsettled: false,\n\t\t\t\t\t\tclassify: () => registry.executionMode(input).kind,\n\t\t\t\t\t\tabandon: () => {\n\t\t\t\t\t\t\treject(/* @__PURE__ */ new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} tool call abandoned`));\n\t\t\t\t\t\t},\n\t\t\t\t\t\tasync start() {\n\t\t\t\t\t\t\texec.agent?.session.append(\"tool/code-dispatch-start\", {\n\t\t\t\t\t\t\t\trootCallId: exec.rootCallId,\n\t\t\t\t\t\t\t\tparentCallId: exec.callId,\n\t\t\t\t\t\t\t\tsubCallId,\n\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\targuments: normalized.logged\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst prepared = await scheduler.prepare(input);\n\t\t\t\t\t\t\tif (prepared.kind === \"dispatch\") {\n\t\t\t\t\t\t\t\tthis.flight = scheduler.dispatch(prepared.exec).then((dispatchOutcome) => {\n\t\t\t\t\t\t\t\t\tparked = {\n\t\t\t\t\t\t\t\t\t\tkind: dispatchOutcome.kind,\n\t\t\t\t\t\t\t\t\t\texec: prepared.exec,\n\t\t\t\t\t\t\t\t\t\tresult: dispatchOutcome.result\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\tthis.settled = true;\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tparked = {\n\t\t\t\t\t\t\t\tkind: prepared.kind,\n\t\t\t\t\t\t\t\texec: prepared.exec,\n\t\t\t\t\t\t\t\tresult: prepared.result\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tthis.settled = true;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tasync commit() {\n\t\t\t\t\t\t\t/* v8 ignore next -- commit() runs only after `settled` flipped, which set parked. */\n\t\t\t\t\t\t\tif (parked === void 0) return;\n\t\t\t\t\t\t\tconst result = parked.kind === \"post-result\" ? await scheduler.finalize(parked.exec, parked.result) : scheduler.finish(parked.exec, parked.result);\n\t\t\t\t\t\t\tfor (const context of result.additionalContexts ?? []) exec.deferContext(context);\n\t\t\t\t\t\t\tif (result.concludesTurn) exec.concludeTurn();\n\t\t\t\t\t\t\tsettle(result);\n\t\t\t\t\t\t\twhile (logWork.size > maxParallel) await Promise.race(logWork);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\twakeup();\n\t\t\t\t\tdrive();\n\t\t\t\t});\n\t\t\t\tif (runOver()) throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} result discarded`);\n\t\t\t\tif (outcome.isError) throw new Error(outcome.message);\n\t\t\t\treturn outcome.value;\n\t\t\t};\n\t\t\tconst functions = Object.create(null);\n\t\t\tfor (const schema of registry.schemas(exec.agent)) {\n\t\t\t\tif (schema.name === \"run_code\") continue;\n\t\t\t\tObject.defineProperty(functions, schema.name, {\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\tvalue: binding(schema.name)\n\t\t\t\t});\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tlet result;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await runtime.run({\n\t\t\t\t\t\tprogram: args.code,\n\t\t\t\t\t\tbindings: [{\n\t\t\t\t\t\t\tglobal: \"tools\",\n\t\t\t\t\t\t\tfunctions,\n\t\t\t\t\t\t\terrorClass: {\n\t\t\t\t\t\t\t\tname: \"ToolCallError\",\n\t\t\t\t\t\t\t\tmemberNameProperty: \"toolName\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}],\n\t\t\t\t\t\tsignal: runController.signal\n\t\t\t\t\t});\n\t\t\t\t} finally {\n\t\t\t\t\trunController.abort(\"run_code settled\");\n\t\t\t\t\tawait drainDispatches();\n\t\t\t\t}\n\t\t\t\tif (result.error) {\n\t\t\t\t\tconst logsText = result.logs.length > 0 ? `\\nCaptured output:\\n${result.logs.join(\"\\n\")}` : \"\";\n\t\t\t\t\tthrow new CodeRunFailedError(`code run failed (${result.error.kind}): ${result.error.message}${logsText}`);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tlogs: result.logs,\n\t\t\t\t\t...result.value !== void 0 ? { result: result.value } : {}\n\t\t\t\t};\n\t\t\t} finally {\n\t\t\t\texec.signal.removeEventListener(\"abort\", onOuterAbort);\n\t\t\t}\n\t\t},\n\t\tpresentCall: (args) => ({\n\t\t\tcard: \"generic\",\n\t\t\ttitle: args.description,\n\t\t\tkind: \"execute\",\n\t\t\trawInput: args.code\n\t\t})\n\t});\n\tObject.defineProperty(definition, \"description\", {\n\t\tenumerable: true,\n\t\tget: () => resolveFlavor(peekRuntime).description\n\t});\n\tObject.defineProperty(definition, \"parameters\", {\n\t\tenumerable: true,\n\t\tget: () => parameterSchemaSpecToJsonSchema({\n\t\t\tcode: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\tdescription: resolveFlavor(peekRuntime).codeDescription\n\t\t\t},\n\t\t\tdescription: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\tdescription: RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION\n\t\t\t}\n\t\t})\n\t});\n\treturn definition;\n}\n//#endregion\n//#region lib/types/ts-types.js\n/**\n* Code Mode codegen: the pure projection from registered tool schemas to the TypeScript SDK\n* text the model programs against (the `tools:sdk` prompt section). Sibling of\n* `json-schema.ts` — `schemas()` (native function calling) and this module (the generated\n* `declare const tools` API) are two projections of the same store.\n* @module @deepseek-ai/dsh-tools/src/ts-types\n*/\n/** Property names that are valid bare TS identifiers; anything else is quoted. */\nconst IDENTIFIER$1 = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n/** Render an object key: bare when it is a valid identifier, quoted otherwise (every name stays reachable, no aliasing). */\nfunction renderKey(name) {\n\treturn IDENTIFIER$1.test(name) ? name : JSON.stringify(name);\n}\n/** One `indent`-deep line prefix (two spaces per level). */\nfunction pad$1(indent) {\n\treturn \" \".repeat(indent);\n}\n/** A one-line JSDoc block for a schema `description`, or no lines when there is none. */\nfunction docLines$1(description, indent) {\n\tif (typeof description !== \"string\" || description.length === 0) return [];\n\tconst collapsed = description.replace(/\\s+/g, \" \").trim();\n\treturn [`${pad$1(indent)}/** ${collapsed.replaceAll(\"*/\", String.raw`*\\/`)} */`];\n}\n/** Render one scalar already validated by the unified schema boundary. */\nfunction renderScalar(value) {\n\treturn JSON.stringify(value);\n}\n/** Render a validated scalar `const`/`enum`, falling back to the broad type. */\nfunction renderConstrainedScalar$1(node, type) {\n\tconst broad = type === \"integer\" ? \"number\" : type;\n\tif (Object.hasOwn(node, \"const\")) return renderScalar(node.const);\n\tif (Object.hasOwn(node, \"enum\")) return node.enum.map(renderScalar).join(\" | \");\n\treturn broad;\n}\n/** Build one document from captured parts while retaining the legacy array-parenthesization test. */\nfunction typeDocumentFrom(parts) {\n\treturn {\n\t\tparts,\n\t\tcontainsUnionOrIntersection: parts.some((part) => typeof part === \"string\" ? part.includes(\"|\") || part.includes(\"&\") : part.containsUnionOrIntersection)\n\t};\n}\n/** Build a small document without an intermediate array at each call site. */\nfunction typeDocument(...parts) {\n\treturn typeDocumentFrom(parts);\n}\n/** Flatten a nested document with an explicit work stack. */\nfunction flattenTypeDocument(document) {\n\tconst chunks = [];\n\tconst tasks = [document];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (typeof task === \"string\") {\n\t\t\tchunks.push(task);\n\t\t\tcontinue;\n\t\t}\n\t\tfor (let index = task.parts.length - 1; index >= 0; index--) {\n\t\t\tconst part = task.parts[index];\n\t\t\t/* v8 ignore next -- the loop is bounded by the captured part count. */\n\t\t\tif (part !== void 0) tasks.push(part);\n\t\t}\n\t}\n\treturn chunks.join(\"\");\n}\n/** Initialize one schema-render frame with empty aggregation state. */\nfunction schemaRenderFrame(node, indent) {\n\treturn {\n\t\tnode,\n\t\tindent,\n\t\tphase: \"start\",\n\t\tchildren: [],\n\t\tchildIndex: 0,\n\t\tchildDocuments: [],\n\t\tentries: []\n\t};\n}\n/** Render an already asserted schema to a composable document. */\nfunction renderSupportedSchema(schema, indent) {\n\tconst frames = [schemaRenderFrame(schema, indent)];\n\tlet rootDocument;\n\tconst finish = (document) => {\n\t\tframes.pop();\n\t\tconst parent = frames.at(-1);\n\t\tif (parent === void 0) rootDocument = document;\n\t\telse parent.childDocuments.push(document);\n\t};\n\twhile (frames.length > 0) {\n\t\tconst frame = frames.at(-1);\n\t\t/* v8 ignore next -- the loop condition guarantees a current frame. */\n\t\tif (frame === void 0) break;\n\t\tif (frame.phase === \"children\") {\n\t\t\tif (frame.childIndex < frame.children.length) {\n\t\t\t\tconst child = frame.children[frame.childIndex];\n\t\t\t\t/* v8 ignore next -- childIndex is bounded by children.length. */\n\t\t\t\tif (child === void 0) throw new Error(\"missing schema render child\");\n\t\t\t\tframe.childIndex++;\n\t\t\t\tframes.push(schemaRenderFrame(child.node, child.indent));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (frame.kind === \"oneOf\") {\n\t\t\t\tconst parts = [];\n\t\t\t\tfor (let index = 0; index < frame.childDocuments.length; index++) {\n\t\t\t\t\tif (index > 0) parts.push(\" | \");\n\t\t\t\t\tconst child = frame.childDocuments[index];\n\t\t\t\t\t/* v8 ignore next -- child documents correspond one-to-one with children. */\n\t\t\t\t\tif (child !== void 0) parts.push(child);\n\t\t\t\t}\n\t\t\t\tfinish(typeDocumentFrom(parts));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (frame.kind === \"array\") {\n\t\t\t\tconst child = frame.childDocuments[0];\n\t\t\t\t/* v8 ignore next -- array frames always schedule exactly one child. */\n\t\t\t\tif (child === void 0) throw new Error(\"missing array item type\");\n\t\t\t\tfinish(child.containsUnionOrIntersection ? typeDocument(\"(\", child, \")[]\") : typeDocument(child, \"[]\"));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst required = new Set(frame.node.required);\n\t\t\tconst parts = [\"{\"];\n\t\t\tfor (let index = 0; index < frame.entries.length; index++) {\n\t\t\t\tconst entry = frame.entries[index];\n\t\t\t\tconst child = frame.childDocuments[index];\n\t\t\t\t/* v8 ignore next -- object entries and child documents have the same length. */\n\t\t\t\tif (entry === void 0 || child === void 0) throw new Error(\"missing object property type\");\n\t\t\t\tconst [name, prop] = entry;\n\t\t\t\tfor (const line of docLines$1(prop.description, frame.indent + 1)) parts.push(\"\\n\", line);\n\t\t\t\tparts.push(\"\\n\", `${pad$1(frame.indent + 1)}${renderKey(name)}${required.has(name) ? \"\" : \"?\"}: `, child, \";\");\n\t\t\t}\n\t\t\tparts.push(\"\\n\", `${pad$1(frame.indent)}}`);\n\t\t\tconst declared = typeDocumentFrom(parts);\n\t\t\tfinish(frame.node.additionalProperties === false ? declared : typeDocument(declared, \" & Record<string, JsonValue>\"));\n\t\t\tcontinue;\n\t\t}\n\t\tconst node = frame.node;\n\t\tif (node.oneOf !== void 0) {\n\t\t\tframe.kind = \"oneOf\";\n\t\t\tframe.children = Array.from(node.oneOf, (child) => ({\n\t\t\t\tnode: child,\n\t\t\t\tindent: frame.indent\n\t\t\t}));\n\t\t\tframe.childIndex = 0;\n\t\t\tframe.childDocuments = [];\n\t\t\tframe.phase = \"children\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (node.type === void 0) {\n\t\t\tfinish(typeDocument(\"JsonValue\"));\n\t\t\tcontinue;\n\t\t}\n\t\tswitch (node.type) {\n\t\t\tcase \"string\":\n\t\t\tcase \"number\":\n\t\t\tcase \"integer\":\n\t\t\tcase \"boolean\":\n\t\t\tcase \"null\":\n\t\t\t\tfinish(typeDocument(renderConstrainedScalar$1(node, node.type)));\n\t\t\t\tbreak;\n\t\t\tcase \"array\":\n\t\t\t\tif (node.items === void 0) finish(typeDocument(\"JsonValue[]\"));\n\t\t\t\telse {\n\t\t\t\t\tframe.kind = \"array\";\n\t\t\t\t\tframe.children = [{\n\t\t\t\t\t\tnode: node.items,\n\t\t\t\t\t\tindent: frame.indent\n\t\t\t\t\t}];\n\t\t\t\t\tframe.childIndex = 0;\n\t\t\t\t\tframe.childDocuments = [];\n\t\t\t\t\tframe.phase = \"children\";\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"object\": {\n\t\t\t\tconst open = node.additionalProperties !== false;\n\t\t\t\tconst entries = Object.entries(node.properties ?? {});\n\t\t\t\tif (entries.length === 0) finish(typeDocument(open ? \"Record<string, JsonValue>\" : \"Record<string, never>\"));\n\t\t\t\telse {\n\t\t\t\t\tframe.kind = \"object\";\n\t\t\t\t\tframe.entries = entries;\n\t\t\t\t\tframe.children = entries.map(([, child]) => ({\n\t\t\t\t\t\tnode: child,\n\t\t\t\t\t\tindent: frame.indent + 1\n\t\t\t\t\t}));\n\t\t\t\t\tframe.childIndex = 0;\n\t\t\t\t\tframe.childDocuments = [];\n\t\t\t\t\tframe.phase = \"children\";\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* v8 ignore next -- assertSupportedJsonSchema narrowed this closed type union. */\n\t\t\tdefault: finish(typeDocument(\"unknown\"));\n\t\t}\n\t}\n\t/* v8 ignore next -- every root frame produces one document. */\n\treturn rootDocument ?? typeDocument(\"unknown\");\n}\n/**\n* Map one enforced JSON-Schema node to a TypeScript type literal. Supports\n* every unified schema construct and returns `unknown` for malformed or\n* unsupported inputs without throwing.\n* @param schema - the JSON-Schema node (any shape; hostile inputs degrade).\n* @param indent - the indentation level for nested object members.\n* @returns the TS type text (multi-line for objects with properties).\n*/\nfunction jsonSchemaToTs(schema, indent = 0) {\n\ttry {\n\t\tassertSupportedJsonSchema(schema);\n\t\treturn flattenTypeDocument(renderSupportedSchema(schema, indent));\n\t} catch {\n\t\treturn \"unknown\";\n\t}\n}\n/** The fixed model-facing usage contract rendered above the declarations (see the Code Mode Agent Note's \"What the model sees\"). */\nconst SDK_INSTRUCTIONS$1 = `## Writing code for run_code\n\n\\`run_code\\` takes two required arguments: \\`code\\` — the body of an async TypeScript function (erasable syntax only — no \\`enum\\` or namespaces; type annotations are advisory, the code runs type-stripped) — and \\`description\\`, a short summary of what the program does. Inside the program:\n\n- Call tools as \\`await tools.name(args)\\` — quoted access for exotic names: \\`tools[\"my-tool\"](args)\\`. Every call resolves to the tool's typed canonical JSON value. Tool arguments must be lossless JSON.\n- A FAILED tool call rejects with \\`ToolCallError\\`, whose \\`toolName\\` identifies the failed tool and whose \\`message\\` is human-readable — \\`try/catch\\` it to handle and continue.\n- Independent read-only calls MAY overlap under \\`Promise.all\\` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with \\`await\\`.\n- Emit results with \\`return\\` and/or \\`console.log(...)\\`. ONLY what you print or return comes back to you — intermediate tool results never enter the conversation, so extract just what you need.\n\nThe available tools:`;\n/**\n* Render the full `tools:sdk` prompt section: the fixed usage instructions\n* plus one `declare const tools` interface covering every given tool.\n* Deterministic — tools are emitted in lexicographic name order, so an\n* unchanged tool set produces byte-identical text across assemblies. The sort\n* is not a total order on byte-equal names, so two schemas sharing a name\n* would render in argument order; the caller's visible-capability map is keyed\n* by name, so the input never carries a duplicate.\n* @param schemas - the tool schemas to declare (the caller excludes\n* `run_code` itself).\n* @returns the complete section text.\n*/\nfunction renderToolsSdk(schemas) {\n\tconst sorted = [...schemas].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);\n\tconst argsMembers = [];\n\tconst outputMembers = [];\n\tfor (const schema of sorted) {\n\t\targsMembers.push(...docLines$1(schema.description, 1));\n\t\targsMembers.push(`${pad$1(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.parameters, 1)};`);\n\t\toutputMembers.push(`${pad$1(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.output, 1)};`);\n\t}\n\treturn `${SDK_INSTRUCTIONS$1}\\n\\n\\`\\`\\`ts\\ntype JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }\\n\\n${[\n\t\t`interface ToolArgsMap {${argsMembers.length > 0 ? `\\n${argsMembers.join(\"\\n\")}\\n` : \"\"}}`,\n\t\t`interface ToolOutputMap {${outputMembers.length > 0 ? `\\n${outputMembers.join(\"\\n\")}\\n` : \"\"}}`,\n\t\t\"type ToolName = keyof ToolOutputMap\",\n\t\t[\n\t\t\t\"declare class ToolCallError extends Error {\",\n\t\t\t\" readonly name: \\\"ToolCallError\\\";\",\n\t\t\t\" readonly toolName: ToolName;\",\n\t\t\t\"}\"\n\t\t].join(\"\\n\"),\n\t\t[\n\t\t\t\"declare const tools: {\",\n\t\t\t\" [K in ToolName]: (args: ToolArgsMap[K]) => Promise<ToolOutputMap[K]>;\",\n\t\t\t\"}\"\n\t\t].join(\"\\n\")\n\t].join(\"\\n\\n\")}\\n\\`\\`\\``;\n}\n//#endregion\n//#region lib/types/py-types.js\n/**\n* Code Mode codegen — Python flavor. The pure projection from registered tool schemas to the\n* Python SDK text the model programs against under `runtime.language === 'python'`. Sibling of\n* {@link ./ts-types.ts | ts-types.ts}; the two files are two projections of the same registry\n* store, keyed by the loaded {@link @deepseek-ai/dsh-code-runtime#CodeRuntime.language | code\n* runtime's language}.\n*\n* Under `mode: 'code'` the native tool schemas are omitted from the request, so this generated\n* SDK is the model's ONLY source for each tool's argument names, required fields, types,\n* descriptions, and canonical output shapes; under `mode: 'both'` the native schemas ship\n* alongside it and it is one of two. Object-shaped arguments and outputs therefore render as one\n* named `TypedDict` per tool (and per nested object), not an opaque `dict[str, Any]`, so the\n* shape survives into the program under the mode that has nothing else to carry it.\n* @module @deepseek-ai/dsh-tools/src/py-types\n*/\n/**\n* The reference grammar's `xid_start xid_continue*` — the set\n* `str.isidentifier()` accepts on a CPython whose Unicode tables match the\n* engine's. See {@link isBareIdentifier} for what a version skew does.\n*/\nconst IDENTIFIER = /^[\\p{XID_Start}_]\\p{XID_Continue}*$/u;\n/**\n* Whether a name can be emitted as a bare Python identifier rather than\n* routed to the subscript/`dict[str, Any]` path.\n*\n* Python identifiers are not ASCII: `路径` is as legal a field name as `path`,\n* and rejecting it would degrade the whole enclosing object, dropping every\n* field's name, requiredness, and type — information whose only source under\n* `mode: 'code'` is this generated text.\n*\n* NFKC stability is a second and separate condition, because CPython\n* normalizes identifiers at compile time while JSON keys are compared as\n* written: `field` would be declared and reachable as `field`, so the SDK would\n* advertise a key under a spelling the harness never accepts, and two keys\n* that normalize together would collapse into one declaration. Those names\n* take the subscript path, which carries their exact bytes.\n*\n* `IDENTIFIER` matches `str.isidentifier()` (measured on Node 22.23.1 vs\n* CPython 3.9.6 tables): the equivalence holds inside the two versions' shared\n* tables, and the skew characters below are exactly where that pair diverges.\n* The predicate as a whole is deliberately stricter than `isidentifier()`,\n* which does not test NFKC stability: `'field'.isidentifier()` is True and\n* this returns false.\n*\n* Both conditions are evaluated against the ENGINE's Unicode tables, and the\n* two sides are versioned independently — `\\p{XID_Start}`/`\\p{XID_Continue}`\n* follow the running engine (Node 22.23.1 reports Unicode 17.0) while CPython\n* follows its own (3.9.6 reports 13.0.0). The skew is not symmetric. A CPython\n* older than the engine is the dangerous direction: a character added to either\n* property since its tables (U+10570 Vithkuqi and U+1E290 Toto, 14.0; U+1E4D0\n* Nag Mundari, 15.0; U+1C89 Cyrillic TJE, 16.0 — ages per `DerivedAge.txt`; all\n* four are NFKC-stable and accepted here, and all four are `Cn` on that 3.9.6,\n* which rejects them) is emitted bare and its tokenizer refuses the character,\n* taking the whole SDK block down — the same parseability invariant\n* {@link UNPRINTABLE}, {@link LONE_SURROGATE} and {@link MAX_LIST_NESTING}\n* exist for. Both properties carry it: a character added only to `XID_Continue`\n* passes the trailing `\\p{XID_Continue}*` in a tail position and fails the same\n* way — U+200C ZWNJ and U+200D ZWJ are that case, gaining `XID_Continue` in UCD\n* 15.1 and absent from it in 13.0.0, 14.0.0 and 15.0.0, so `a\\u{200C}b` is\n* emitted bare here while `isidentifier()` is False on 3.9.6 and on 3.12.13\n* (15.0.0). A CPython newer than the engine only routes a legal name to the\n* subscript/`dict[str, Any]` path: less readable, still correct. The NFKC\n* condition reduces to the same skew, since normalization stability guarantees\n* an assigned character's normalization never changes afterwards.\n*\n* This predicate is not the only reader of engine tables. {@link camelCase}\n* reads them at three further points — its split set, its head test, and its\n* `toUpperCase()` case mapping — and this predicate's verdict gates none of\n* them: a class name derived there reaches emitted text whenever any object\n* shape in the tool's schema declares a `TypedDict`, including for a tool this\n* predicate rejected. A tool named `zz-\\u{1E4D0}x` with such parameters never\n* reaches the skew here (the `-` rejects it outright) yet emits `class\n* Zz\\u{1E4D0}xArgs`, which that same 3.9.6 refuses — Nag Mundari arrived two\n* releases after its tables. The case mapping is a separate table rather than\n* an XID membership test, and it fails on names both conditions above accept:\n* `\\u{019B}` is XID_Start and NFKC-stable, so this predicate accepts it and\n* `async def \\u{019B}` compiles on 3.9.6, but Node uppercases it to\n* `\\u{A7DC}` — unassigned in that CPython, whose own `.upper()` is the identity\n* here — and the declared `class \\u{A7DC}Args` fails with `invalid\n* non-printable character U+A7DC`. Closing the exposure therefore covers all\n* four read points, not this predicate alone; it needs the target interpreter's\n* version, which the backend reporting `language: 'python'` owns; the\n* language-dispatch Agent Note records the deferral.\n*\n* The `ts-types` sibling keeps its own ASCII rule rather than sharing this\n* one: ECMAScript identifiers are a different set (`$`) and are never\n* normalized, so one predicate cannot be correct for both. ZWJ/ZWNJ are not\n* part of that difference — both sets carry them on the engine's tables; what\n* separates the two there is the CPython table version above.\n* @param name - the raw schema field or tool name.\n* @returns whether the name can be emitted bare.\n*/\nfunction isBareIdentifier(name) {\n\treturn IDENTIFIER.test(name) && name.normalize(\"NFKC\") === name;\n}\n/**\n* Python hard keywords: reserved everywhere, so a tool or field named\n* ``class`` or ``lambda`` is legal on the wire but not as an attribute\n* (``tools.class`` would be a SyntaxError in the model program) and not as a\n* class-syntax `TypedDict` field. Such a tool renders under subscript access\n* and such an object degrades to ``dict[str, Any]`` — the model still reaches\n* every tool and field without collisions.\n* Soft keywords (``match``, ``case``, ``type``, ``_`` — the language\n* reference's whole set) are deliberately ABSENT: each is special in exactly\n* one syntactic position — a statement head (``match``, ``type``), a ``match``\n* statement's clause head (``case``), or a pattern (``_``) — so ``match: str``\n* as a field and ``async def match(...)`` as a method are both legal, and\n* including them would needlessly degrade common search/regex tool fields to\n* ``dict[str, Any]``. Underscore-leading names are handled separately, not\n* here: a non-dunder ``__token`` name-mangles, a dunder present on\n* ``object``/``type`` resolves before the proxy hook, and implicit\n* special-method lookup bypasses the hook.\n*/\nconst RESERVED = new Set([\n\t\"False\",\n\t\"None\",\n\t\"True\",\n\t\"and\",\n\t\"as\",\n\t\"assert\",\n\t\"async\",\n\t\"await\",\n\t\"break\",\n\t\"class\",\n\t\"continue\",\n\t\"def\",\n\t\"del\",\n\t\"elif\",\n\t\"else\",\n\t\"except\",\n\t\"finally\",\n\t\"for\",\n\t\"from\",\n\t\"global\",\n\t\"if\",\n\t\"import\",\n\t\"in\",\n\t\"is\",\n\t\"lambda\",\n\t\"nonlocal\",\n\t\"not\",\n\t\"or\",\n\t\"pass\",\n\t\"raise\",\n\t\"return\",\n\t\"try\",\n\t\"while\",\n\t\"with\",\n\t\"yield\",\n\t\"__debug__\"\n]);\n/** `typing` symbols this module may emit, in the deterministic import order. */\nconst TYPING_ORDER = [\n\t\"Any\",\n\t\"Literal\",\n\t\"NotRequired\",\n\t\"Protocol\",\n\t\"TypedDict\"\n];\n/** `indent`-deep line prefix (four spaces per level to match PEP 8 output). */\nfunction pad(indent) {\n\treturn \" \".repeat(indent);\n}\n/**\n* The `Cc` code points that survive the whitespace collapse in {@link describe}\n* and have no printable form: the C0 controls, DEL, and the C1 controls. Only\n* U+0009 to U+000D are absent, because ECMAScript `\\s` already collapsed them —\n* `\\s` is TAB/VT/FF/SP/NBSP/ZWNBSP/Zs plus LF/CR/LS/PS, so no C1 code point is\n* in it and the whole U+0080 to U+009F block reaches this rule intact. Those\n* are not hypothetical input: they are what Windows-1252 bytes 0x80 to 0x9F\n* (smart quotes, em dash) become when decoded as Latin-1.\n* CPython rejects source containing a NUL outright\n* (`SyntaxError: source code string cannot contain null bytes`), whether it\n* sits in a docstring or in a comment, so one such byte anywhere in a schema\n* description would make the whole generated SDK unparseable — under\n* `mode: 'code'`, the model's only declaration of the tools. The rest are\n* legal but invisible; escaping them with the same rule keeps the emitted text\n* readable and the treatment uniform.\n*\n* The boundary is the category, not per-code-point addressability: `\\xNN`\n* addresses U+0000 to U+00FF, so one escape form covers `Cc` exactly. The\n* invisible `Cf` formatting characters pass through by design — of them only\n* U+00AD soft hyphen would fit `\\xNN` at all, and escaping that one while\n* U+200B ZWSP, U+200E/U+200F bidi marks, and U+2060 word joiner passed through\n* would leave a rule that is neither category- nor addressability-shaped. The\n* whole family is legal in both consumers, since only LF and CR terminate a\n* Python string literal or a `#` comment. That set is the tokenizer's, not\n* `str.splitlines()`': NEL (U+0085), LS (U+2028), and PS (U+2029) split a\n* string at run time but do not end a physical line in source — measured on\n* CPython 3.9.6 and 3.12.13, each accepted in both positions with the value\n* round-tripping — so they are safe raw wherever they reach emitted text\n* unescaped, which for all three is `JSON.stringify`, at two call sites:\n* {@link pyScalar}'s literal path, and the subscript tool-name comment's own\n* call, which a name carrying any of them always reaches, none being\n* `XID_Continue`. The `description` path escapes NEL under the class above and\n* folds LS and PS in {@link describe}'s `\\s+` collapse, both being `\\s`.\n*/\nconst UNPRINTABLE = /[\\u0000-\\u0008\\u000e-\\u001f\\u007f-\\u009f]/g;\n/**\n* Unpaired surrogate code points, escaped by {@link describe} as `\\uNNNN` —\n* its own form, since `\\xNN` stops at U+00FF. The `u` flag is what makes this\n* the LONE ones: in Unicode mode a well-formed pair is a single astral code\n* point outside D800 to DFFF, so an emoji in a description survives untouched.\n*\n* This is the NUL case from {@link UNPRINTABLE}, not the invisible-character\n* case. Python source must be UTF-8-encodable and a lone surrogate is not, so\n* `compile()` raises `UnicodeEncodeError: surrogates not allowed` for one\n* anywhere in the text — measured on 3.9 for a string literal and for a `#`\n* comment alike. A raw or MCP tool description reaches this: `JSON.parse` on a\n* wire `\"\\ud800\"` escape yields exactly such a code point.\n*/\nconst LONE_SURROGATE = /[\\ud800-\\udfff]/gu;\n/**\n* The collapsed one-line `description` of a schema node (byte-stable across\n* formatting churn), or `undefined` when the node carries none. Every caller\n* passes an object — a validated property node, the `ToolSdkSchema` itself, or\n* the `{ description }` wrapper {@link docLines} synthesizes — so only the\n* description field needs guarding. A description that collapses\n* to nothing (empty, or whitespace only) is `undefined` too: it documents the\n* node no better than an absent one, and emitting it would leave an empty\n* `\"\"\"` docstring or a bare `# ` line in the SDK. Only ECMAScript whitespace\n* folds, so a description of whitespace plus one surviving control character is\n* NOT absent: it collapses to that character's visible escape.\n*\n* Control characters left over after the whitespace collapse are rendered as\n* their `\\xNN` escapes (see {@link UNPRINTABLE}) and unpaired surrogates as\n* their `\\uNNNN` escapes (see {@link LONE_SURROGATE}); the escape's own backslash is\n* emitted literally by both consumers, since {@link docLines} doubles it into a\n* Python source escape and a `#` comment carries it verbatim.\n*/\nfunction describe(schema) {\n\tconst description = schema.description;\n\tif (typeof description !== \"string\") return void 0;\n\tconst collapsed = description.replace(/\\s+/g, \" \").replace(UNPRINTABLE, (char) => `\\\\x${char.charCodeAt(0).toString(16).padStart(2, \"0\")}`).replace(LONE_SURROGATE, (char) => `\\\\u${char.charCodeAt(0).toString(16).padStart(4, \"0\")}`).trim();\n\treturn collapsed.length === 0 ? void 0 : collapsed;\n}\n/**\n* One-line docstring for a tool `description`, or no lines when there is none.\n* Backslashes are doubled first, every quote is escaped, and a trailing\n* backslash cannot survive: a description ending in `\"` or an odd backslash\n* would otherwise merge with (or escape) the closing triple quote and make\n* the generated block — Code Mode's only SDK — syntactically invalid Python.\n*/\nfunction docLines(description, indent) {\n\tconst collapsed = describe({ description });\n\tif (collapsed === void 0) return [];\n\tconst escaped = collapsed.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"\\\"\", \"\\\\\\\"\");\n\treturn [`${pad(indent)}\"\"\"${escaped}\"\"\"`];\n}\n/**\n* CamelCase a name into a Python type identifier: non-identifier characters\n* split words, `_` splits too (it is `XID_Continue`, so the split set names it\n* explicitly), and a head that cannot start an identifier takes a `Tool`\n* prefix. Unicode survives, so a `路径` field yields `路径`-based class names\n* instead of collapsing to the bare prefix. A character that is not\n* `XID_Continue` splits even when it is a letter, so a name whose NFKC folding\n* would leave the identifier set is not carried through — the split set is the\n* grammar's, not an ASCII approximation of it.\n*\n* The result is NFKC-normalized: these names are generated, never matched\n* against a JSON key, so normalizing is free here and keeps what CPython\n* compiles identical to what is emitted — unlike {@link isBareIdentifier},\n* which must reject unstable names outright. Normalizing AFTER the prefix\n* decision is what makes that hold at the seam the prefix creates: `Tool` +\n* a combining-mark head composes there (`U+0301` gives `Tooĺ`, U+013A), so\n* normalizing only the un-prefixed part would emit a name CPython compiles to\n* a different symbol. The second call is idempotent on the un-prefixed arm.\n*\n* The split set, the head test, and `toUpperCase()` all read the engine's\n* Unicode tables, so this function carries the same version skew\n* {@link isBareIdentifier} documents, by paths independent of it: a class name\n* derived here reaches emitted text whenever any object shape in the tool's\n* schema declares a `TypedDict`, and the predicate's verdict on the tool name\n* does not gate that. The case mapping is the one that can fail on a name the\n* predicate accepted; the worked example is there.\n* @param raw - the schema field or tool name to derive from.\n* @returns a class-name segment safe to emit.\n*/\nfunction camelCase(raw) {\n\tconst joined = raw.split(/[^\\p{XID_Continue}]+|_+/u).filter((part) => part.length > 0).map((part) => `${part.charAt(0).toUpperCase()}${part.slice(1)}`).join(\"\").normalize(\"NFKC\");\n\treturn (/^\\p{XID_Start}/u.test(joined) ? joined : `Tool${joined}`).normalize(\"NFKC\");\n}\n/** Class-name base cap keeping each emitted name — and total text — linear in schema depth. */\nconst MAX_CLASS_NAME_BASE = 120;\n/**\n* Deepest `list[…]` nesting emitted into one annotation before the item type\n* degrades to `Any`. CPython's tokenizer rejects a logical line holding more\n* than 200 simultaneously-open brackets (`MAXLEVEL`, `SyntaxError: too many\n* nested parentheses`), so an array chain deeper than that would render an SDK\n* block that is not valid Python at all — the same failure the docstring\n* escaping in {@link docLines} exists to prevent. 180 leaves headroom for the\n* few brackets an annotation can add around the chain, all of which count\n* toward the same limit. Per emission site, counting brackets open at the\n* chain's innermost point:\n*\n* - Return annotation, `async def f(self, args: X) -> chain:` — 180 `list[`\n* plus an innermost `Literal[`. The parameter list's `(` closed at the `)`\n* before the `->`, so it is NOT open here: 181.\n* - TypedDict field, `field: NotRequired[chain]` — a class-body line with no\n* other open bracket, and its children start at `listDepth: 1` to reserve\n* the `NotRequired[`, so 179 `list[` plus `Literal[`: 181. Required fields\n* share that start for uniformity, spending one level of representable depth\n* on a bracket they never emit.\n* - Argument annotation, `async def f(self, args: chain) -> Y:` — the `(` IS\n* still open around it: 180 `list[` plus `Literal[` plus the paren, 182, the\n* worst case. Reachable only through a raw `register()` whose `parameters`\n* is an array reached from the root through `oneOf` arms alone — the root\n* array itself, or one nested under any depth of unions, since an arm\n* inherits the enclosing depth unchanged (`A | B` opens no bracket). An\n* object ancestor takes it out of this case: its fields restart the chain at\n* the 181 site. `defineTool` compiles an object root, so the annotation is a\n* bare TypedDict class name or a one-bracket `dict[str, Any]` when that\n* object degrades — never a chain.\n*\n* A CPython grammar limit, not a deployment choice, so it is fixed rather than\n* configurable. The sibling `ts-types` renderer needs no counterpart: nothing\n* in the TypeScript grammar bounds nesting, and its SDK block is never type-\n* checked. Only bracket nesting counts — a `oneOf` renders as a flat `A | B`\n* chain and nested objects render as separate `class` statements, so neither\n* accumulates open brackets at any depth. The invariant this cap serves is\n* grammatical validity; see the `oneOf` arm in {@link renderType} for the one\n* interpreter limit deliberately left uncapped.\n*/\nconst MAX_LIST_NESTING = 180;\n/**\n* Cap a class-name base at {@link MAX_CLASS_NAME_BASE} (see the callers for\n* why capping keeps the render linear). `slice` counts UTF-16 code units, so\n* an astral character straddling the boundary would be cut in half and leave a\n* lone surrogate — not an identifier character, and not even well-formed text;\n* drop it rather than emit it.\n*/\nfunction capClassNameBase(base) {\n\tif (base.length <= MAX_CLASS_NAME_BASE) return base;\n\tconst capped = base.slice(0, MAX_CLASS_NAME_BASE);\n\treturn /[\\uD800-\\uDBFF]$/.test(capped) ? capped.slice(0, -1) : capped;\n}\n/**\n* Reserve a unique class name from a base, suffixing `2`, `3`, … on collision.\n* The base is capped at {@link MAX_CLASS_NAME_BASE} first: child class names\n* derive from their parent's allocated name (`ParentChild`), so an unbounded\n* schema of single-field objects would otherwise grow each name by one field\n* per level and the sum of all names to Θ(depth²). Capping the base keeps each\n* name — and the total emitted text — linear in depth. Collisions resume from\n* the per-base counter in `state.nextClassCounter` rather than rescanning from\n* `2`, so a deep chain sharing one capped base stays O(1) per allocation\n* (amortized) instead of Θ(depth²) in time.\n*/\nfunction allocateClassName(base, state) {\n\tconst capped = capClassNameBase(base);\n\tlet name = capped;\n\tif (state.usedClassNames.has(name)) {\n\t\tlet n = state.nextClassCounter.get(capped) ?? 2;\n\t\twhile (state.usedClassNames.has(`${capped}${n}`)) n++;\n\t\tname = `${capped}${n}`;\n\t\tstate.nextClassCounter.set(capped, n + 1);\n\t}\n\tstate.usedClassNames.add(name);\n\treturn name;\n}\n/**\n* Append a child-name segment to a parent class-name base, capping the result\n* at {@link MAX_CLASS_NAME_BASE}. Capping AT PROPAGATION (not only inside\n* {@link allocateClassName}) keeps each level O(1): a deep `oneOf`- or\n* object-chain would otherwise carry an ever-growing ConsString down the tree\n* and re-materialize it (via `.length`/`.slice`) at every level — Θ(depth²).\n* The bounded base plus the collision counter still yields unique names.\n*\n* The join is NFKC-normalized because both sides are separately normalized yet\n* their concatenation need not be: a base ending in a Hangul L jamo or LV\n* syllable composes with a following V or T jamo head (`가` + `ᆨ` gives `각`),\n* so the emitted class name would differ from the symbol CPython compiles, and\n* two byte-distinct names could fold onto one — `usedClassNames` dedupes by the\n* raw bytes, so the collision counter would not see it. Normalizing costs\n* O(cap + segment) per level, the same order as the `slice` it feeds. The other\n* two join points need no counterpart: `Args`/`Output` start with `A`/`O` and\n* {@link allocateClassName}'s suffix is digits, none of which compose backwards.\n*/\nfunction childClassName(base, segment) {\n\treturn capClassNameBase(`${base}${segment}`.normalize(\"NFKC\"));\n}\n/**\n* Render one validated scalar as Python literal text (`True`/`False`,\n* JSON-quoted strings, bare numbers). `null` cannot reach here: the `null`\n* type renders directly as `None`, and the unified validator rejects a null\n* `const`/`enum` entry on every other scalar type.\n*\n* A beyond-safe-range integral number takes `BigInt` digits rather than\n* `String`: Python integers are arbitrary-precision, so the emitted digits ARE\n* the value the model programs against, and `String` can give a different\n* integer than the double holds (`2 ** 60` prints the rounded `...847000`, not\n* the exact `...846976`) or no integer literal at all (`1e21` prints `1e+21`).\n* `String`'s rounding is not a bug in it: `Number::toString` emits the shortest\n* decimal string that re-reads to the same double, then pads to the exponent\n* with zeros (1 significant digit for `1e20`, 16 for `2 ** 60`) — and when the\n* shortest string is shorter than the double's exact value, those padded digits\n* name an integer no double holds. Passing one back would have to cross the\n* argument boundary as a JSON number — a double again — so the SDK would\n* document a value no program can pass. `BigInt` needs no case split: where\n* `String` is already exact (`2 ** 53`, `1e20`) the two agree byte for byte,\n* and where it is not, `BigInt` is the exact one. The TS flavor needs no\n* counterpart at all: its literal is re-read by a JS parser back into the same\n* double.\n*\n* `JSON.stringify` is also what keeps this path's output parseable, and it is\n* the only thing that does. It covers both classes of hazard: the two kinds of\n* code point CPython refuses anywhere in source — NUL among the C0 controls,\n* and the whole D800–DFFF unpaired-surrogate block, escaped under ES2019\n* well-formed stringification, which the engines range guarantees — and the\n* ones that break this line in particular, a bare `\"` closing the literal\n* early, a trailing odd backslash eating the closing quote, and a bare LF/CR\n* ending it before its terminator. The `description` path carries\n* {@link UNPRINTABLE} and {@link LONE_SURROGATE} because nothing quotes it,\n* and folds newlines in {@link describe}.\n*\n* That leans on a coincidence worth naming: every escape `JSON.stringify` can\n* emit (`\\\"`, `\\\\`, `\\b`, `\\f`, `\\n`, `\\r`, `\\t`, `\\uXXXX`) is also a Python\n* escape denoting the same character, so the emitted `Literal[...]` both\n* parses and decodes back to the value the schema declared. DEL, the C1\n* controls (NEL among them), and LS/PS (U+2028/U+2029) do reach it raw —\n* legal but invisible, byte-for-byte as in the TS flavor; escaping them is a\n* both-flavors change. Those last three are legal here for the reason\n* {@link UNPRINTABLE} records: they are `str.splitlines()` boundaries, not\n* tokenizer line terminators. The subscript tool-name comment quotes its name\n* through its own call to the same `JSON.stringify`, never through this\n* function, and inherits both halves — escapes and pass-throughs alike.\n*/\nfunction pyScalar(value) {\n\tif (value === true) return \"True\";\n\tif (value === false) return \"False\";\n\tif (typeof value === \"string\") return JSON.stringify(value);\n\tif (typeof value === \"number\" && Number.isInteger(value) && !Number.isSafeInteger(value)) return BigInt(value).toString();\n\treturn String(value);\n}\n/**\n* Render a validated scalar `const`/`enum` as `Literal[...]`, falling back to\n* the broad type. Deliberately deviates from PEP 586, which restricts `Literal`\n* parameters to int/bool/str/bytes/enum/None: a non-integral number\n* `const`/`enum` emits a float literal (`Literal[1.5]`) a strict checker would\n* reject. An integral one does not deviate — {@link pyScalar} emits int digits,\n* including for the beyond-safe-range values it widens through `BigInt`, and\n* PEP 586 admits int parameters. Harmless either way — the stub is advisory\n* prompt text, only required to parse — and keeping the exact value\n* communicates the constraint to the model.\n*/\nfunction renderConstrainedScalar(node, broad, state) {\n\tif (node.const !== void 0) {\n\t\tstate.typing.add(\"Literal\");\n\t\treturn `Literal[${pyScalar(node.const)}]`;\n\t}\n\tif (node.enum !== void 0) {\n\t\tstate.typing.add(\"Literal\");\n\t\treturn `Literal[${node.enum.map(pyScalar).join(\", \")}]`;\n\t}\n\treturn broad;\n}\n/**\n* Map one JSON-Schema node to a Python type expression, threading `state` to\n* collect the `TypedDict` declarations and `typing` symbols a full render\n* needs. `className` is the name to give an object node with properties (and\n* the prefix for its nested objects). Handles every unified schema construct —\n* `oneOf` (→ `X | Y`), `const`/`enum` (→ `Literal[...]`), `integer` (→ `int`),\n* `null` (→ `None`) — and degrades an unsupported or malformed schema to `Any`\n* without throwing, the same trusted-after-validation stance as the sibling\n* {@link ./ts-types.ts | ts-types} renderer. {@link jsonSchemaToPy} is the\n* context-free entry point; this is the collecting core.\n*/\nfunction renderType(schema, className, state) {\n\tconst newFrame = (schema, className, listDepth) => ({\n\t\tschema,\n\t\tclassName,\n\t\tphase: \"start\",\n\t\tlistDepth,\n\t\tchildren: [],\n\t\tchildIndex: 0,\n\t\tchildTypes: [],\n\t\tentries: []\n\t});\n\ttry {\n\t\tassertSupportedJsonSchema(schema);\n\t\tconst frames = [newFrame(schema, className, 0)];\n\t\tlet result;\n\t\tconst finish = (type) => {\n\t\t\tframes.pop();\n\t\t\tconst parent = frames.at(-1);\n\t\t\tif (parent === void 0) result = type;\n\t\t\telse parent.childTypes.push(type);\n\t\t};\n\t\twhile (frames.length > 0) {\n\t\t\tconst frame = frames.at(-1);\n\t\t\t/* v8 ignore next -- the loop condition guarantees a current frame. */\n\t\t\tif (frame === void 0) break;\n\t\t\tif (frame.phase === \"children\") {\n\t\t\t\tif (frame.childIndex < frame.children.length) {\n\t\t\t\t\tconst child = frame.children[frame.childIndex];\n\t\t\t\t\t/* v8 ignore next -- childIndex is bounded by children.length. */\n\t\t\t\t\tif (child === void 0) throw new Error(\"missing python render child\");\n\t\t\t\t\tframe.childIndex++;\n\t\t\t\t\tframes.push(newFrame(child.schema, child.className, child.listDepth));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (frame.kind === \"oneOf\") {\n\t\t\t\t\tlet union = \"\";\n\t\t\t\t\tfor (const [index, childType] of frame.childTypes.entries()) union = index === 0 ? childType : `${union} | ${childType}`;\n\t\t\t\t\tfinish(union);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (frame.kind === \"array\") {\n\t\t\t\t\t/* v8 ignore next -- the ?? arm needs a childless array frame, which start never builds. */\n\t\t\t\t\tfinish(`list[${frame.childTypes[0] ?? \"Any\"}]`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst node = frame.node;\n\t\t\t\tconst name = frame.allocated;\n\t\t\t\t/* v8 ignore next -- typeddict frames always set node and allocated at start. */\n\t\t\t\tif (node === void 0 || name === void 0) throw new Error(\"missing typeddict frame state\");\n\t\t\t\tconst required = new Set(node.required);\n\t\t\t\tconst lines = [`class ${name}(TypedDict):`];\n\t\t\t\tfor (let index = 0; index < frame.entries.length; index++) {\n\t\t\t\t\tconst entry = frame.entries[index];\n\t\t\t\t\tconst fieldType = frame.childTypes[index];\n\t\t\t\t\t/* v8 ignore next -- entries and childTypes correspond one-to-one. */\n\t\t\t\t\tif (entry === void 0 || fieldType === void 0) throw new Error(\"missing typeddict field type\");\n\t\t\t\t\tconst [field, fieldSchema] = entry;\n\t\t\t\t\tconst description = describe(fieldSchema);\n\t\t\t\t\tif (description !== void 0) lines.push(`${pad(1)}# ${description}`);\n\t\t\t\t\tif (required.has(field)) lines.push(`${pad(1)}${field}: ${fieldType}`);\n\t\t\t\t\telse {\n\t\t\t\t\t\tstate.typing.add(\"NotRequired\");\n\t\t\t\t\t\tlines.push(`${pad(1)}${field}: NotRequired[${fieldType}]`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (node.additionalProperties !== false) lines.push(`${pad(1)}# Additional keys beyond those declared are allowed.`);\n\t\t\t\tif (lines.length === 1) lines.push(`${pad(1)}pass`);\n\t\t\t\tstate.classes.push(lines.join(\"\\n\"));\n\t\t\t\tfinish(name);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tframe.phase = \"children\";\n\t\t\tconst node = frame.schema;\n\t\t\tif (node.oneOf !== void 0) {\n\t\t\t\tframe.kind = \"oneOf\";\n\t\t\t\tframe.children = node.oneOf.map((branch, index) => ({\n\t\t\t\t\tschema: branch,\n\t\t\t\t\tclassName: childClassName(frame.className, `${index + 1}`),\n\t\t\t\t\tlistDepth: frame.listDepth\n\t\t\t\t}));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (node.type === void 0) {\n\t\t\t\tstate.typing.add(\"Any\");\n\t\t\t\tfinish(\"Any\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tswitch (node.type) {\n\t\t\t\tcase \"string\":\n\t\t\t\t\tfinish(renderConstrainedScalar(node, \"str\", state));\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"number\":\n\t\t\t\t\tfinish(renderConstrainedScalar(node, \"float\", state));\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"integer\":\n\t\t\t\t\tfinish(renderConstrainedScalar(node, \"int\", state));\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"boolean\":\n\t\t\t\t\tfinish(renderConstrainedScalar(node, \"bool\", state));\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"null\":\n\t\t\t\t\tfinish(\"None\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"array\":\n\t\t\t\t\tif (node.items === void 0) {\n\t\t\t\t\t\tstate.typing.add(\"Any\");\n\t\t\t\t\t\tfinish(\"list[Any]\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (frame.listDepth >= MAX_LIST_NESTING) {\n\t\t\t\t\t\tstate.typing.add(\"Any\");\n\t\t\t\t\t\tfinish(\"Any\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tframe.kind = \"array\";\n\t\t\t\t\tframe.children = [{\n\t\t\t\t\t\tschema: node.items,\n\t\t\t\t\t\tclassName: frame.className,\n\t\t\t\t\t\tlistDepth: frame.listDepth + 1\n\t\t\t\t\t}];\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"object\": {\n\t\t\t\t\tconst entries = Object.entries(node.properties ?? {});\n\t\t\t\t\tif (className === \"\" || !entries.every(([name]) => isBareIdentifier(name) && !RESERVED.has(name) && !(name.startsWith(\"__\") && !name.endsWith(\"__\")))) {\n\t\t\t\t\t\tstate.typing.add(\"Any\");\n\t\t\t\t\t\tfinish(\"dict[str, Any]\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (entries.length === 0 && node.additionalProperties !== false) {\n\t\t\t\t\t\tstate.typing.add(\"Any\");\n\t\t\t\t\t\tfinish(\"dict[str, Any]\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tframe.kind = \"typeddict\";\n\t\t\t\t\tframe.node = node;\n\t\t\t\t\tframe.allocated = allocateClassName(frame.className, state);\n\t\t\t\t\tstate.typing.add(\"TypedDict\");\n\t\t\t\t\tframe.entries = entries;\n\t\t\t\t\t/* v8 ignore next -- allocated is always set before children are built. */\n\t\t\t\t\tframe.children = entries.map(([field, child]) => ({\n\t\t\t\t\t\tschema: child,\n\t\t\t\t\t\tclassName: childClassName(frame.allocated ?? \"\", camelCase(field)),\n\t\t\t\t\t\tlistDepth: 1\n\t\t\t\t\t}));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t/* v8 ignore next 4 -- assertSupportedJsonSchema narrowed this closed type union. */\n\t\t\t\tdefault:\n\t\t\t\t\tstate.typing.add(\"Any\");\n\t\t\t\t\tfinish(\"Any\");\n\t\t\t}\n\t\t}\n\t\t/* v8 ignore next -- every root frame produces one expression. */\n\t\treturn result ?? \"Any\";\n\t} catch {\n\t\tstate.typing.add(\"Any\");\n\t\treturn \"Any\";\n\t}\n}\n/**\n* Map one JSON-Schema node to a context-free Python type expression from the\n* `typing` module. Handles every unified schema construct — `object` (degraded\n* to `dict[str, Any]`: naming a `TypedDict` requires the render context that\n* {@link renderToolsSdkPy} supplies), `const`/`enum` (→ `Literal[...]`),\n* `oneOf` (→ union), `string`/`number`/`integer`/`boolean`/`null`, `array`\n* (`items` → `list[T]`) — and returns `Any` for an unsupported or malformed\n* schema, matching the TS flavor's `unknown` fallback. Type annotations in the\n* emitted SDK are advisory: Python does not enforce them at runtime.\n* @param schema - the JSON-Schema node.\n* @returns the Python type text.\n*/\nfunction jsonSchemaToPy(schema) {\n\treturn renderType(schema, \"\", {\n\t\tclasses: [],\n\t\tusedClassNames: /* @__PURE__ */ new Set(),\n\t\tnextClassCounter: /* @__PURE__ */ new Map(),\n\t\ttyping: /* @__PURE__ */ new Set()\n\t});\n}\n/** The fixed model-facing usage contract rendered above the declarations. */\nconst SDK_INSTRUCTIONS = `## Writing code for run_code\n\n\\`run_code\\` takes two required arguments: \\`code\\` — the body of an async Python function (top-level \\`await\\` and \\`return\\` both work) — and \\`description\\`, a short summary of what the program does. At run time exactly two of the names declared below are bound: \\`tools\\` and \\`ToolCallError\\`. Everything else is a STATIC STUB describing argument and return types — in particular the \\`TypedDict\\` classes do NOT exist at run time, so build arguments as plain \\`dict\\`/\\`list\\` JSON values: \\`await tools.name({\"field\": 1})\\`, never \\`FooArgs(field=1)\\`, which raises \\`NameError\\`. Inside the program:\n\n- Call tools as \\`await tools.name(args)\\` — subscript access for exotic, reserved, or underscore-leading names: \\`await tools[\"my-tool\"](args)\\`. Every call resolves to the tool's typed canonical JSON value (each method's return type below). Tool arguments must be lossless JSON.\n- A FAILED tool call raises \\`ToolCallError\\`, whose \\`toolName\\` identifies the failed tool and whose message is human-readable — wrap in \\`try/except\\` to handle and continue.\n- Independent read-only calls MAY overlap under \\`asyncio.gather\\` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with \\`await\\`.\n- Emit the run's answer with \\`print(...)\\` and/or a top-level \\`return <value>\\`; the returned value must be lossless JSON. ONLY what you print and the returned value come back — intermediate tool results never enter the conversation, so extract just what you need.\n\nThe available tools:`;\n/**\n* Render the full `tools:sdk` prompt section under `runtime.language ===\n* 'python'`: the Python-flavored usage instructions plus one named `TypedDict`\n* per tool argument or output object (and per nested object) and one awaitable\n* method per visible tool on a `Tools` protocol — typed args in, the tool's\n* canonical output value out — with a `tools: Tools` singleton the model calls\n* into. The `typing` import line lists exactly the symbols the render used.\n* Deterministic — tools are emitted in lexicographic name order, and class\n* declarations precede the protocol in that same order (nested classes before\n* the parent that references them), so an unchanged tool set produces\n* byte-identical text across assemblies. The sort is not a total order on\n* byte-equal names, so two schemas sharing a name would render in argument\n* order; the caller's visible-capability map is keyed by name, so the input\n* never carries a duplicate.\n* @param schemas - the tool schemas plus canonical output schemas to declare\n* (the caller excludes `run_code` itself).\n* @returns the complete section text.\n*/\nfunction renderToolsSdkPy(schemas) {\n\tconst sorted = [...schemas].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);\n\tconst state = {\n\t\tclasses: [],\n\t\tusedClassNames: /* @__PURE__ */ new Set(),\n\t\tnextClassCounter: /* @__PURE__ */ new Map(),\n\t\ttyping: new Set([\"Protocol\"])\n\t};\n\tconst members = [];\n\tlet statements = 0;\n\tfor (const schema of sorted) {\n\t\tconst argType = renderType(schema.parameters, `${camelCase(schema.name)}Args`, state);\n\t\tconst outputType = renderType(schema.output, `${camelCase(schema.name)}Output`, state);\n\t\tif (isBareIdentifier(schema.name) && !RESERVED.has(schema.name) && !schema.name.startsWith(\"_\")) {\n\t\t\tconst doc = docLines(schema.description, 2);\n\t\t\tmembers.push(doc.length > 0 ? `${pad(1)}async def ${schema.name}(self, args: ${argType}) -> ${outputType}:` : `${pad(1)}async def ${schema.name}(self, args: ${argType}) -> ${outputType}: ...`);\n\t\t\tmembers.push(...doc);\n\t\t\tstatements += 1;\n\t\t} else {\n\t\t\tmembers.push(`${pad(1)}# tools[${JSON.stringify(schema.name)}](args: ${argType}) -> ${outputType}`);\n\t\t\tconst description = describe(schema);\n\t\t\tif (description !== void 0) members.push(`${pad(1)}# ${description}`);\n\t\t}\n\t}\n\tconst body = (statements > 0 ? members : [`${pad(1)}pass`, ...members]).join(\"\\n\");\n\tconst imports = TYPING_ORDER.filter((symbol) => state.typing.has(symbol));\n\tconst classBlock = state.classes.length > 0 ? `${state.classes.join(\"\\n\\n\")}\\n\\n` : \"\";\n\treturn `${SDK_INSTRUCTIONS}\\n\\n\\`\\`\\`python\\n${`from typing import ${imports.join(\", \")}\\n\\nclass ToolCallError(Exception):\n toolName: str\\n\\n${classBlock}class Tools(Protocol):\\n${body}\\n\\ntools: Tools`}\\n\\`\\`\\``;\n}\n//#endregion\n//#region lib/types/testing.js\n/** Canonical tool-definition fixtures for repository tests. @module dsh-tools/testing */\nconst CONTENT_VALUE_SCHEMA = {\n\ttype: \"array\",\n\titems: { type: \"json\" }\n};\n/**\n* Define a test fixture that deliberately uses its content blocks as the\n* canonical JSON value. Product tools must declare domain-owned DTOs instead.\n* @param options - ordinary fixture fields plus a content-producing body.\n* @returns a registry-ready tool with an explicit JSON-array output contract.\n* @internal\n*/\nfunction defineContentToolFixture(options) {\n\tconst execute = options.execute;\n\treturn defineTool({\n\t\t...options,\n\t\toutput: {\n\t\t\tschema: CONTENT_VALUE_SCHEMA,\n\t\t\trender: (_args, value) => value\n\t\t},\n\t\tasync execute(args, exec) {\n\t\t\treturn await execute(args, exec);\n\t\t}\n\t});\n}\n//#endregion\n//#region lib/types/index.js\n/**\n* Tool registry, model presentation modes, and pre/guard/around/post/result\n* execution pipeline.\n* @module @deepseek-ai/dsh-tools\n*/\n/**\n* Language → SDK-section renderer. The registry looks up the loaded\n* `ctx.codeRuntime.language` in this table when assembling the `tools:sdk`\n* section under a non-native mode; a runtime whose language is not a key\n* fails the assembly loudly (same idiom as `toolOrder` violations). Adding a\n* new backend language is three parallel edits — a {@link CodeSdkLanguage}\n* member, an entry here, and a `RUN_CODE_FLAVORS` entry in `code-mode.ts` for\n* its `run_code` schema strings — plus the renderer function this table points\n* at. The `satisfies` clause pins this table's key set to that union, which\n* the flavor table is checked against too, so any of the three left out is a\n* typecheck failure. What no check reaches is the prose that names the values\n* instead of deriving them: the seam's `dsh-code-runtime` README pair, its\n* `CodeRuntime.language` JSDoc, and `docs/subsystems/code-runtime.md`\n* with its zh pair, plus this package's own README pair and the\n* {@link Config.mode} JSDoc.\n*/\n/**\n* Prompt order of the `code` collapse statement: after the persona and before\n* the 100-199 per-tool guidance band, so the model reads which tools it may\n* call before it reads what each one is for.\n*/\nconst COLLAPSE_SECTION_ORDER = 99;\n/**\n* The model-facing statement of the `code` collapse. Names the consequence\n* (the call fails) and the route (inside the program), because a rule the\n* model can only discover by being denied is one it corrects too late.\n*/\nconst CODE_ONLY_INSTRUCTION = `\\`${RUN_CODE_NAME}\\` is the only tool you can call directly — a tool call naming any other tool fails. Reach every tool the SDK declares below from inside the program.`;\nconst SDK_RENDERERS = {\n\ttypescript: renderToolsSdk,\n\tpython: renderToolsSdkPy\n};\n/**\n* Scheduler entry point omitted from the generated named service API.\n* @internal\n*/\nconst TOOL_RUNTIME_SCHEDULER = Symbol(\"@deepseek-ai/dsh-tools.scheduler\");\n/** Canonical error code for cancellation after a tool body was invoked. */\nconst TOOL_ABORTED = \"ABORTED\";\n/** Canonical error code for cancellation before a tool body was invoked. */\nconst TOOL_ABORTED_BEFORE_DISPATCH = \"ABORTED_BEFORE_DISPATCH\";\n/**\n* Thrown (internally) when the model requests a tool that isn't registered.\n* Extends {@link HarnessError} (`code: 'UNKNOWN_TOOL'`) so an unknown-tool\n* failure is as routable as a tool-thrown one — retry/sandbox/replay code can\n* distinguish it from a tool body's own error.\n*/\nvar ToolNotFoundError = class extends HarnessError {\n\t/**\n\t* @param toolName - the name the caller asked for.\n\t* @param reachableFrom - how the model reaches this tool instead, when the\n\t* name IS visible and only the presentation denies calling it directly.\n\t* Omitted for a name that is registered nowhere.\n\t*/\n\tconstructor(toolName, reachableFrom) {\n\t\tsuper(reachableFrom === void 0 ? `unknown tool \"${toolName}\"` : `unknown tool \"${toolName}\": ${reachableFrom}`, \"UNKNOWN_TOOL\");\n\t\tthis.name = \"ToolNotFoundError\";\n\t}\n};\n/** Thrown when a tool body or post-policy value violates its declared output. */\nvar ToolOutputError = class extends HarnessError {\n\t/** Schema/value violations in validation order. */\n\tviolations;\n\tconstructor(toolName, violations) {\n\t\tsuper(`tool \"${toolName}\" returned invalid output: ${violations.join(\"; \")}`, \"INVALID_TOOL_OUTPUT\");\n\t\tthis.name = \"ToolOutputError\";\n\t\tthis.violations = violations;\n\t}\n};\n/** Convert one projector exception into the canonical invalid-output failure. */\nfunction projectionError(toolName, projector, error) {\n\treturn new ToolOutputError(toolName, [`output.${projector} failed: ${errorMessage(error)}`]);\n}\n/** Snapshot one projector result before later durable-result materialization. */\nfunction snapshotProjection(toolName, projector, candidate) {\n\ttry {\n\t\tconst detached = snapshotJsonValue(candidate);\n\t\tif (detached === void 0) throw new ToolOutputError(toolName, [`output.${projector} returned non-lossless JSON`]);\n\t\treturn detached;\n\t} catch (error) {\n\t\tif (error instanceof ToolOutputError) throw error;\n\t\tthrow projectionError(toolName, projector, error);\n\t}\n}\n/** Snapshot one body or policy value into the canonical invalid-output failure class. */\nfunction snapshotToolValue(toolName, candidate) {\n\ttry {\n\t\tconst detached = snapshotJsonValue(candidate);\n\t\tif (detached === void 0) throw new ToolOutputError(toolName, [\"value is not lossless JSON\"]);\n\t\treturn detached;\n\t} catch (error) {\n\t\tif (error instanceof ToolOutputError) throw error;\n\t\tthrow new ToolOutputError(toolName, [`value snapshot failed: ${errorMessage(error)}`]);\n\t}\n}\n/**\n* Best-effort human-readable message from an arbitrary thrown value: Error\n* instances use `.message`; non-Error objects with a string `message`\n* property (e.g. `throw { message: 'denied' }`) use it too; everything else\n* is stringified.\n*/\nfunction errorMessage(error) {\n\ttry {\n\t\tif (error instanceof Error) return error.message;\n\t\tif (typeof error === \"object\" && error !== null && \"message\" in error && typeof error.message === \"string\") return error.message;\n\t\treturn String(error);\n\t} catch {\n\t\treturn \"<unprintable thrown value>\";\n\t}\n}\n/** Derive one failure message from policy feedback without changing its rendered blocks. */\nfunction failureMessageFromContent(content) {\n\tconst text = content.map((block) => block.type === \"text\" ? block.text : `[${block.type} content]`).join(\"\\n\");\n\treturn text.length > 0 ? text : \"tool result blocked by post-execute policy\";\n}\n/** Snapshot and freeze one durable tool-result projection or reject lossy data. */\nfunction materializePresentation(candidate) {\n\tconst detached = snapshotJsonValue(candidate);\n\tif (detached === void 0) throw new TypeError(\"tool result must be losslessly JSON-serializable\");\n\treturn deepFreeze(detached);\n}\n/** Structured `{ name, code }` for a thrown HarnessError, else undefined. */\nfunction errorInfo(error) {\n\ttry {\n\t\treturn error instanceof HarnessError ? {\n\t\t\tname: error.name,\n\t\t\tcode: error.code\n\t\t} : void 0;\n\t} catch {\n\t\treturn;\n\t}\n}\n/** One scope's complete tool-registry contribution. */\nvar ToolLayer = class {\n\ttools;\n\trestrictions = new AnonymousEntries();\n\tguards = new AnonymousEntries();\n\t/**\n\t* Presentation this scope's agent declared for itself, shadowing the\n\t* deployment default. One cell rather than an entry table: two answers to\n\t* \"which form does the model see\" is a contradiction, not a merge.\n\t*/\n\tmode;\n\tconstructor(scope) {\n\t\tthis.tools = new NamedEntries((name) => /* @__PURE__ */ new Error(scope === void 0 ? `tool \"${name}\" is already registered (for a per-agent variant, register through that agent's \\`agent.ctx\\` instead)` : `tool \"${name}\" is already registered in this scope`));\n\t}\n\t/** Whether every contribution table in this aggregate layer is empty. */\n\tisEmpty() {\n\t\treturn this.tools.isEmpty() && this.restrictions.isEmpty() && this.guards.isEmpty() && this.mode === void 0;\n\t}\n\t/** Whether every compiled restriction in this layer admits a global tool name. */\n\tadmits(name) {\n\t\tfor (const filter of this.restrictions.values()) if (filter.allow !== void 0 && !filter.allow.has(name) || filter.deny !== void 0 && filter.deny.has(name)) return false;\n\t\treturn true;\n\t}\n\t/** First monotonic denial from this layer's live guard registrations. */\n\tguardReason(exec) {\n\t\tfor (const guard of this.guards.values()) {\n\t\t\tconst reason = guard(exec);\n\t\t\tif (reason !== void 0) return reason;\n\t\t}\n\t}\n};\n/** Resolve the run_code overlap cap at the owning config boundary (direct construction bypasses the Loader schema). */\nfunction resolveMaxParallelSubCalls(value) {\n\tconst maxParallelSubCalls = value ?? 10;\n\tif (!Number.isInteger(maxParallelSubCalls) || maxParallelSubCalls < 1) throw new Error(\"maxParallelSubCalls must be a positive integer\");\n\treturn maxParallelSubCalls;\n}\n/**\n* Tool registry and execution pipeline. Scoped registrations shadow globals;\n* one visibility resolver feeds presentation, lookup, and dispatch.\n*/\nvar ToolRuntime = class extends Service {\n\tstatic inject = [\"systemPrompt\"];\n\tstatic Config = z.object({\n\t\tmode: z.union([\n\t\t\t\"native\",\n\t\t\t\"code\",\n\t\t\t\"both\"\n\t\t]).default(\"native\"),\n\t\tmaxParallelSubCalls: z.natural().min(1).default(10)\n\t});\n\t/** Internal staged view consumed by `dsh-agent-loop`'s parallel scheduler. */\n\t[TOOL_RUNTIME_SCHEDULER] = {\n\t\tprepare: (exec) => this.prepareScheduledExecution(exec),\n\t\tdispatch: (exec) => this.dispatchScheduledExecution(exec),\n\t\tfinalize: (exec, result) => this.finalizeScheduledExecution(exec, result),\n\t\tfinish: (exec, result) => this.finishScheduledExecution(exec, result)\n\t};\n\t/** Context deferred by a running tool body, keyed by its scheduler-owned execution. */\n\tdeferredContexts = /* @__PURE__ */ new WeakMap();\n\t/** Executions whose tool body declared the current turn complete. */\n\tconcludingExecutions = /* @__PURE__ */ new WeakSet();\n\t/** Original caller cancellation, kept outside the wrapper-mutable execution object. */\n\tcancellationStates = /* @__PURE__ */ new WeakMap();\n\t/** Definition-owned final content transform snapshotted before policy begins. */\n\tcontentFinalizers = /* @__PURE__ */ new WeakMap();\n\tlayers = new ScopedLayers((scope) => new ToolLayer(scope), () => {\n\t\tthis.ctx.emit(\"tools/change\");\n\t});\n\t/** Presentation for scopes that declare none; {@link presentAs} shadows it per scope. */\n\tdefaultMode;\n\tmaxParallelSubCalls;\n\t/**\n\t* Reserved presentation transport, kept outside the filterable registration\n\t* layers. Built on first need rather than at construction: which agents run\n\t* a code mode is no longer known when the service is constructed, and the\n\t* transport is stateless beyond its closures over `this`.\n\t*/\n\tcodeTransport;\n\tconstructor(ctx, config = {}) {\n\t\tsuper(ctx, \"tools\");\n\t\tthis.defaultMode = config.mode ?? \"native\";\n\t\tthis.maxParallelSubCalls = resolveMaxParallelSubCalls(config.maxParallelSubCalls);\n\t\tctx.systemPrompt.tools((context) => this.wireSchemas(context.scope));\n\t\tif (this.defaultMode !== \"native\") {\n\t\t\tctx.systemPrompt.section(this.collapseSection());\n\t\t\tctx.systemPrompt.section(this.sdkSection());\n\t\t}\n\t}\n\t/**\n\t* The prompt statement of the `code` executor collapse, registered wherever\n\t* {@link sdkSection} is and rendering empty outside an effective `code`.\n\t*\n\t* Every tool contributes its own guidance section naming its tool, none of\n\t* them qualify how that tool is reached, and they all render before the SDK\n\t* (orders 100-199 against {@link SDK_SECTION_ORDER}). Without this the model\n\t* reads a catalog of tools it is told to use and no statement that only\n\t* `run_code` may be called, so it emits a native call, receives\n\t* `UNKNOWN_TOOL` for a tool the prompt just declared, and concludes the\n\t* deployment is inconsistent. {@link COLLAPSE_SECTION_ORDER} places the rule\n\t* before that guidance rather than after it.\n\t*\n\t* `both` renders empty: native calls do execute there, so the rule is false.\n\t* @returns the section registration.\n\t*/\n\tcollapseSection() {\n\t\treturn {\n\t\t\tname: \"tools:code-only\",\n\t\t\torder: COLLAPSE_SECTION_ORDER,\n\t\t\ttext: (context) => this.modeFor(context.scope) === \"code\" ? CODE_ONLY_INSTRUCTION : \"\"\n\t\t};\n\t}\n\t/**\n\t* The generated-SDK prompt section, registered globally by a code-mode\n\t* deployment and per scope by {@link presentAs}.\n\t*\n\t* The body regenerates from the CALLING scope, and renders empty for an\n\t* agent presenting natively — an agent that opted out under a code-mode\n\t* deployment still sees the global registration, and an empty section is\n\t* dropped from the rendered prompt.\n\t* @returns the section registration.\n\t*/\n\tsdkSection() {\n\t\treturn {\n\t\t\tname: \"tools:sdk\",\n\t\t\torder: 150,\n\t\t\ttext: (context) => {\n\t\t\t\tconst mode = this.modeFor(context.scope);\n\t\t\t\tif (mode === \"native\") return \"\";\n\t\t\t\tconst runtime = this.requireCodeRuntime(mode);\n\t\t\t\tconst render = SDK_RENDERERS[runtime.language];\n\t\t\t\t/* v8 ignore next -- requireCodeRuntime rejects an unknown language before this runs. */\n\t\t\t\tif (render === void 0) throw new Error(`dsh-tools: no SDK renderer for ${runtime.language}`);\n\t\t\t\treturn render(this.sdkSchemas(context.scope));\n\t\t\t}\n\t\t};\n\t}\n\t/**\n\t* The presentation one scope's agent sees: its own declaration, else the\n\t* deployment default.\n\t* @param scope - the calling agent, or undefined for the global view.\n\t* @returns the resolved presentation mode.\n\t*/\n\tmodeFor(scope) {\n\t\tconst layers = this.layers.chainLayers(scope);\n\t\tfor (let index = layers.length - 1; index >= 0; index -= 1) {\n\t\t\tconst mode = layers[index]?.mode;\n\t\t\tif (mode !== void 0) return mode;\n\t\t}\n\t\treturn this.defaultMode;\n\t}\n\t/**\n\t* The reserved `run_code` transport, built on first need.\n\t*\n\t* It never enters the global layer: per-agent restrictions must not remove\n\t* it, and a scoped registration must not shadow it. The visibility resolver\n\t* appends it after resolving the filterable global/scoped capability layers,\n\t* and only for scopes whose mode actually presents it.\n\t* @returns the shared transport definition.\n\t*/\n\trequireCodeTransport() {\n\t\tthis.codeTransport ??= createRunCodeTool(this, {\n\t\t\trequireRuntime: () => this.requireCodeRuntime(this.defaultMode),\n\t\t\tpeekRuntime: () => this.ctx.get(\"codeRuntime\"),\n\t\t\tmaxParallel: this.maxParallelSubCalls,\n\t\t\tshapeDispatchLog: (dispatch) => this.shapeDispatchLog(dispatch)\n\t\t});\n\t\treturn this.codeTransport;\n\t}\n\t/**\n\t* Present the calling scope's tools in `mode` instead of the deployment\n\t* default. Nearest scope on the chain wins, so a preset's standing\n\t* declaration covers every agent joined under it.\n\t*\n\t* Scoped only, and one declaration per scope: this is how an agent preset\n\t* composes Code Mode agents beside native ones in the same process, and a\n\t* process-global override would be the `mode` config field instead.\n\t* @param mode - the presentation the covered agents' models see.\n\t* @returns the exact disposer that restores the deployment default.\n\t*/\n\tpresentAs(mode) {\n\t\tconst ctx = this.ctx;\n\t\tif (scopeOf(ctx) === void 0) throw new Error(\"tools.presentAs() requires a scoped context (agent.ctx): a context-global presentation is the `mode` config field on the tools row\");\n\t\treturn ctx.effect(function* () {\n\t\t\tyield this.layers.effect(ctx, (layer) => {\n\t\t\t\tif (layer.mode !== void 0) throw new Error(`tools.presentAs(\"${mode}\") conflicts with \"${layer.mode}\" already declared for this scope; one composition selects one presentation`);\n\t\t\t\tlayer.mode = mode;\n\t\t\t\treturn () => {\n\t\t\t\t\tlayer.mode = void 0;\n\t\t\t\t};\n\t\t\t}, { label: \"tools.presentAs()\" });\n\t\t\tif (mode !== \"native\") {\n\t\t\t\tyield ctx.systemPrompt.section(this.collapseSection());\n\t\t\t\tyield ctx.systemPrompt.section(this.sdkSection());\n\t\t\t}\n\t\t}.bind(this), \"tools.presentAs()\");\n\t}\n\t/**\n\t* Build one scope's wire schemas and names for prompt-order validation.\n\t* Restrictions do not make known tools invalid, but a mode collapse does.\n\t*/\n\twireSchemas(scope) {\n\t\tconst view = this.view(scope);\n\t\tconst mode = this.modeFor(scope);\n\t\tif (mode === \"native\") return {\n\t\t\tschemas: [...view.visible.values()].map((definition) => this.schemaOf(definition, false)),\n\t\t\tknownNames: [...view.knownNames]\n\t\t};\n\t\tthis.requireCodeRuntime(mode);\n\t\tconst schemas = [...view.visible.values()].map((definition) => this.schemaOf(definition, false));\n\t\tif (mode === \"code\") return {\n\t\t\tschemas: schemas.filter((schema) => schema.name === RUN_CODE_NAME),\n\t\t\tknownNames: [RUN_CODE_NAME]\n\t\t};\n\t\treturn {\n\t\t\tschemas,\n\t\t\tknownNames: [...view.knownNames, RUN_CODE_NAME]\n\t\t};\n\t}\n\t/**\n\t* Resolve the code runtime or throw the actionable misconfiguration error.\n\t* Read at use time (assembly / run_code execution), NOT via static\n\t* `inject`: an inject entry would hold `ctx.tools` — and every tool plugin\n\t* behind it — hostage to a code runtime existing even under `mode:\n\t* 'native'` (the loop's optional-backend idiom, same as\n\t* `sessionPersistence`).\n\t*\n\t* Assembly and `run_code` execution read separately, so the language is not\n\t* bound to a request. Harmless while one published backend exists — both\n\t* reads return the same flavor — but a reload that swapped in a second\n\t* language between them would hand a program written against one SDK to the\n\t* other. Binding it is deferred until a second backend ships (the first\n\t* point it is testable); rationale in the\n\t* [language-dispatch note](../../../../.agents/notes/implemented/feature/2026-07-31-code-mode-language-dispatch.md).\n\t*/\n\trequireCodeRuntime(mode) {\n\t\tconst runtime = this.ctx.get(\"codeRuntime\");\n\t\tif (!runtime) throw new Error(`dsh-tools: mode \"${mode}\" requires a code runtime — load a ctx.codeRuntime implementation (e.g. @deepseek-ai/dsh-code-runtime-worker-thread) or set tools mode to \"native\"`);\n\t\tif (!Object.hasOwn(SDK_RENDERERS, runtime.language)) {\n\t\t\tconst known = Object.keys(SDK_RENDERERS).map((name) => JSON.stringify(name)).join(\", \");\n\t\t\tthrow new Error(`dsh-tools: no SDK renderer registered for runtime language ${JSON.stringify(runtime.language)} (known: ${known})`);\n\t\t}\n\t\treturn runtime;\n\t}\n\t/**\n\t* Register globally or in the calling agent scope. Scoped tools shadow\n\t* globals; duplicates within one layer and the reserved `run_code` name fail.\n\t* @param definition - tool schema, execution, and optional finalization/presentation callbacks.\n\t* @returns the exact disposer that unregisters the tool.\n\t*/\n\tregister(definition) {\n\t\tconst name = definition.name;\n\t\tconst output = definition.output;\n\t\tif (output === void 0 || typeof output !== \"object\" || typeof output.render !== \"function\" || output.presentationMeta !== void 0 && typeof output.presentationMeta !== \"function\") throw new TypeError(`tool \"${name}\" must declare output { schema, render, presentationMeta? }`);\n\t\tassertSupportedJsonSchema(output.schema);\n\t\tconst timeoutMs = definition.timeoutMs;\n\t\tif (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) throw new TypeError(`tool \"${name}\" timeoutMs must be a positive finite number`);\n\t\tif (name === \"run_code\") throw new Error(`tool name \"${RUN_CODE_NAME}\" is reserved for the Code Mode presentation transport and cannot be registered or shadowed`);\n\t\treturn this.layers.effect(this.ctx, (layer) => layer.tools.insert(name, definition), { label: \"tools.register()\" });\n\t}\n\t/**\n\t* Restrict global tools for the calling agent scope. Empty filters, unknown\n\t* names, scope-local names, and reserved transport names fail. Restrictions\n\t* intersect; scoped registrations remain visible.\n\t* @param filter - global-tool mask: `allow` (keep only) and/or `deny` (remove).\n\t* @returns the exact disposer that lifts this restriction.\n\t*/\n\trestrict(filter) {\n\t\tconst scope = scopeOf(this.ctx);\n\t\tif (scope === void 0) throw new Error(\"tools.restrict() requires a scoped context (agent.ctx): a context-global restriction would mask every agent — deny the tool for the intended agent instead\");\n\t\tconst allow = filter.allow;\n\t\tconst deny = filter.deny;\n\t\tif (allow === void 0 && deny === void 0) throw new Error(\"tools.restrict({}) is a no-op: pass `allow` and/or `deny` (an empty filter is almost always a materialized-empty-config bug)\");\n\t\tconst compiled = {\n\t\t\t...allow !== void 0 ? { allow: new Set(allow) } : {},\n\t\t\t...deny !== void 0 ? { deny: new Set(deny) } : {}\n\t\t};\n\t\tif ([...allow ?? [], ...deny ?? []].includes(\"run_code\")) throw new Error(`tools.restrict() cannot name reserved Code Mode presentation transport \"${RUN_CODE_NAME}\"; restrict end-capability tools instead`);\n\t\tconst known = this.view(scope).restrictableNames;\n\t\tconst unknown = [...allow ?? [], ...deny ?? []].filter((name) => !known.has(name));\n\t\tif (unknown.length > 0) throw new Error(`tools.restrict() names unknown global tool${unknown.length > 1 ? \"s\" : \"\"} ${unknown.map((n) => `\"${n}\"`).join(\", \")}; known global tools: ${[...known].sort().join(\", \") || \"(none)\"}`);\n\t\treturn this.layers.effect(this.ctx, (layer) => layer.restrictions.append(compiled), { label: \"tools.restrict()\" });\n\t}\n\t/**\n\t* Register a monotonic guard after the extensible `tools/pre-execute`\n\t* waterfall. A plain-context guard applies globally; one registered through\n\t* `agent.ctx` applies only to that agent. Any matching guard may deny by\n\t* returning a reason, while no guard can force-allow a call another guard\n\t* denied. The exact effect disposer is returned for ordered ownership and\n\t* HMR cleanup.\n\t* @param guard - synchronous check; a returned string denies the execution.\n\t* @returns the exact disposer that unregisters the guard.\n\t*/\n\tguard(guard) {\n\t\treturn this.layers.effect(this.ctx, (layer) => layer.guards.append(guard), {\n\t\t\tlabel: \"tools.guard()\",\n\t\t\tnotify: false\n\t\t});\n\t}\n\t/** First monotonic denial from the global then the scope chain's guard layers, farthest first. */\n\tguardReason(exec) {\n\t\tconst globalReason = this.layers.global.guardReason(exec);\n\t\tif (globalReason !== void 0) return globalReason;\n\t\tif (exec.agent === void 0) return void 0;\n\t\tfor (const layer of this.layers.chainLayers(exec.agent)) {\n\t\t\tconst reason = layer.guardReason(exec);\n\t\t\tif (reason !== void 0) return reason;\n\t\t}\n\t}\n\t/**\n\t* Resolve every registry fact one scope needs in one layer traversal. The\n\t* visible map applies restrictions to the INHERITED surface, then the\n\t* scope's own registrations and the reserved presentation transport; the\n\t* other sets retain the pre-restriction facts needed by restriction and\n\t* prompt-order validation.\n\t*\n\t* A restriction filters what a scope inherits — the global layer and every\n\t* ancestor layer on its chain — and never what its OWN layer registers.\n\t* That exemption is what a per-child capability filter has to keep intact:\n\t* the delegation runtime registers a child's reporting and structured-output\n\t* tools into the child's own layer, and a filter naming the capabilities the\n\t* child may use must not strip the machinery it answers through.\n\t*\n\t* Reading the exempt set as \"the global layer\" instead of \"not mine\" held\n\t* only while every model-facing tool sat in the host composition. Once\n\t* presets moved them onto the agent plane they became an ANCESTOR\n\t* contribution, so a child's filter silently stopped constraining anything\n\t* it was given.\n\t* @param scope - the viewing scope (the agent), or undefined for the global view.\n\t* @returns the complete derived view for that scope.\n\t*/\n\tview(scope) {\n\t\tconst layers = this.layers.chainLayers(scope);\n\t\tconst own = this.layers.peek(scope);\n\t\tconst inherited = new Map(this.layers.global.tools.entries());\n\t\tfor (const layer of layers) {\n\t\t\tif (layer === own) continue;\n\t\t\tfor (const [name, definition] of layer.tools.entries()) inherited.set(name, definition);\n\t\t}\n\t\tconst visible = /* @__PURE__ */ new Map();\n\t\tconst knownNames = /* @__PURE__ */ new Set();\n\t\tconst restrictableNames = /* @__PURE__ */ new Set();\n\t\tfor (const [name, definition] of inherited) {\n\t\t\tknownNames.add(name);\n\t\t\trestrictableNames.add(name);\n\t\t\tif (layers.every((layer) => layer.admits(name))) visible.set(name, definition);\n\t\t}\n\t\tif (own !== void 0) for (const [name, definition] of own.tools.entries()) {\n\t\t\tknownNames.add(name);\n\t\t\tvisible.set(name, definition);\n\t\t}\n\t\tif (this.modeFor(scope) !== \"native\") visible.set(RUN_CODE_NAME, this.requireCodeTransport());\n\t\treturn {\n\t\t\tvisible,\n\t\t\tknownNames,\n\t\t\trestrictableNames\n\t\t};\n\t}\n\t/**\n\t* Look up a tool as one scope sees it (scoped\n\t* shadows global; a restricted-away global reads as absent). Presenters pass\n\t* the calling agent so the rendered card matches the definition that\n\t* actually executed.\n\t* @param name - the tool name as registered.\n\t* @param scope - the viewing scope (the agent); omitted = the global view.\n\t* @returns the definition the scope resolves, or undefined when none is visible.\n\t*/\n\tget(name, scope) {\n\t\treturn this.view(scope).visible.get(name);\n\t}\n\t/**\n\t* Resolve the definition that MAY EXECUTE for a call, applying the mode\n\t* collapse at the operation boundary that owns it. The registry view\n\t* (`get`) is presentation-agnostic; here a MODEL-DIRECT call under `code`\n\t* may only name the reserved `run_code` transport, while a nested\n\t* sub-dispatch (a `parent` token set — the `run_code` SDK calling a tool\n\t* it bound) may call any visible tool. Denial surfaces as `UNKNOWN_TOOL`\n\t* through the executor, matching an absent definition.\n\t* @param name - the tool name as registered.\n\t* @param scope - the viewing scope (the agent); omitted = the global view.\n\t* @param nested - whether the call is a transport sub-dispatch, not a model-direct call.\n\t* @returns the definition that may run, or undefined when the call must be rejected.\n\t*/\n\tresolveExecution(name, scope, nested) {\n\t\tconst tool = this.get(name, scope);\n\t\tif (tool === void 0) return void 0;\n\t\tif (this.collapses(name, scope, nested)) return void 0;\n\t\treturn tool;\n\t}\n\t/**\n\t* Project visible definitions onto the allowlisted model-facing schema fields,\n\t* excluding execution and presentation callbacks.\n\t* @param scope - the viewing scope (the agent); omitted = the global view.\n\t* @returns one deep-cloned schema per visible tool.\n\t*/\n\tschemas(scope) {\n\t\treturn [...this.view(scope).visible.values()].map((definition) => this.schemaOf(definition, true));\n\t}\n\t/** Project visible callable tools onto the generated Code Mode SDK contract. */\n\tsdkSchemas(scope) {\n\t\treturn [...this.view(scope).visible.values()].filter((definition) => definition.name !== RUN_CODE_NAME).map((definition) => {\n\t\t\tconst output = snapshotJsonValue(definition.output.schema);\n\t\t\t/* v8 ignore next -- registration already validated and retained this schema as lossless JSON. */\n\t\t\tif (output === void 0) throw new Error(`tool \"${definition.name}\" output schema must be lossless JSON before SDK projection`);\n\t\t\treturn {\n\t\t\t\t...this.schemaOf(definition, true),\n\t\t\t\toutput\n\t\t\t};\n\t\t});\n\t}\n\t/** Project one definition onto the model-facing schema fields. */\n\tschemaOf(definition, detachParameters) {\n\t\tconst { name, description, parameters } = definition;\n\t\tconst detached = detachParameters ? snapshotJsonValue(parameters) : parameters;\n\t\tif (detached === void 0) throw new Error(`tool \"${name}\" parameters must be lossless JSON before schema projection`);\n\t\treturn {\n\t\t\tname,\n\t\t\tdescription,\n\t\t\tparameters: detached\n\t\t};\n\t}\n\t/**\n\t* Classify a pending call through the caller's visible tool definition. Only\n\t* an exact `true` is parallel; unknown, hidden, undeclared, invalid, or\n\t* throwing classifiers are exclusive.\n\t* @param exec - call name, parsed arguments, and optional agent scope.\n\t* @returns the fail-closed scheduling mode.\n\t*/\n\texecutionMode(exec) {\n\t\tconst tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== void 0);\n\t\tif (!tool?.isConcurrencySafe) return { kind: \"exclusive\" };\n\t\ttry {\n\t\t\treturn tool.isConcurrencySafe(exec.arguments) === true ? { kind: \"parallel\" } : { kind: \"exclusive\" };\n\t\t} catch {\n\t\t\treturn { kind: \"exclusive\" };\n\t\t}\n\t}\n\t/**\n\t* Run the `tools/code-dispatch-log` waterfall over one settled sub-dispatch\n\t* and return the content the bridge should log on `tool/code-dispatch`.\n\t* Contained: when a listener throws, the method logs the original settled\n\t* content; that failure must not fail the dispatch or omit the settle event. Private:\n\t* the ONE consumer is the `run_code` bridge this registry constructs, which\n\t* receives it as a capability parameter (the `requireRuntime` idiom) — the\n\t* waterfall, not this invoker, is the public extension point.\n\t*/\n\tasync shapeDispatchLog(dispatch) {\n\t\ttry {\n\t\t\treturn await this.ctx.waterfall(scopeTarget(this, dispatch.agent), \"tools/code-dispatch-log\", dispatch, () => Promise.resolve(dispatch.content));\n\t\t} catch (error) {\n\t\t\tthis.ctx.logger.warn(`tools: code-dispatch-log listener failed for ${dispatch.name}: ${errorMessage(error)}; logging the original settled content`);\n\t\t\treturn dispatch.content;\n\t\t}\n\t}\n\t/**\n\t* Whether the `code` mode collapse denies a model-direct call: only the\n\t* reserved `run_code` transport may be named. Nested sub-dispatches (a\n\t* `parent` token set) bypass the collapse. One home for the\n\t* security-relevant predicate, shared by {@link resolveExecution} and\n\t* {@link createExecution} so the two can never drift apart.\n\t*\n\t* Resolved through {@link modeFor}, NOT `defaultMode`: an agent given `code`\n\t* by an agent preset under a native deployment is the composition\n\t* `dsh-agent-tool-presentation` exists for, and reading the deployment default would\n\t* leave exactly that agent uncollapsed — announcing one surface while\n\t* executing another, which is the bypass this collapse closes.\n\t* @param name - the tool name as registered.\n\t* @param scope - the viewing scope whose effective presentation mode applies.\n\t* @param nested - whether the call is a transport sub-dispatch, not a model-direct call.\n\t*/\n\tcollapses(name, scope, nested) {\n\t\treturn !nested && this.modeFor(scope) === \"code\" && name !== \"run_code\";\n\t}\n\t/**\n\t* Execute through pre-policy, guards, around-dispatch, post-policy,\n\t* definition-owned content finalization, and final notification. Tool and\n\t* listener failures resolve as materialized error results; an invisible tool\n\t* reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen\n\t* snapshot final observers receive. Cancellation\n\t* arriving after entry and before final result materialization skips a\n\t* not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a\n\t* successful started outcome with `ABORTED`; already-started work is still\n\t* drained and may retain a tool-owned structured error.\n\t* @param exec - the typed same-process call input. The registry assigns its\n\t* correlation token before policy begins.\n\t* @returns the materialized final result.\n\t*/\n\tasync execute(exec) {\n\t\treturn this.prepareExecution(exec, (prepared) => this.completeScheduledExecution(prepared));\n\t}\n\tasync completeScheduledExecution(prepared) {\n\t\tswitch (prepared.kind) {\n\t\t\tcase \"dispatch\": {\n\t\t\t\tconst dispatched = await this.dispatchScheduledExecution(prepared.exec);\n\t\t\t\treturn dispatched.kind === \"post-result\" ? await this.finalizeScheduledExecution(prepared.exec, dispatched.result) : this.finishScheduledExecution(prepared.exec, dispatched.result);\n\t\t\t}\n\t\t\tcase \"post-result\": return await this.finalizeScheduledExecution(prepared.exec, prepared.result);\n\t\t\tcase \"final-result\": return this.finishScheduledExecution(prepared.exec, prepared.result);\n\t\t\t/* v8 ignore next -- closed-union exhaustiveness guard */\n\t\t\tdefault: return assertNever(prepared, \"scheduled tool preparation\");\n\t\t}\n\t}\n\tcreateExecution(exec) {\n\t\tconst deferredContexts = [];\n\t\tconst token = createExecutionToken();\n\t\tconst callId = exec.callId;\n\t\tconst rootCallId = exec.rootCallId ?? callId;\n\t\tconst name = exec.name;\n\t\tconst agent = exec.agent;\n\t\tconst parent = exec.parent;\n\t\tconst signal = exec.signal;\n\t\tconst visible = this.get(name, agent);\n\t\tconst collapsed = visible !== void 0 && this.collapses(name, agent, parent !== void 0);\n\t\tconst concludingExecutions = this.concludingExecutions;\n\t\tconst base = {\n\t\t\ttoken,\n\t\t\tcallId,\n\t\t\trootCallId,\n\t\t\tname,\n\t\t\tsignal,\n\t\t\t...agent !== void 0 ? { agent } : {},\n\t\t\t...parent !== void 0 ? { parent } : {},\n\t\t\tdeferContext(context) {\n\t\t\t\tdeferredContexts.push(context);\n\t\t\t},\n\t\t\tconcludeTurn() {\n\t\t\t\tconcludingExecutions.add(this);\n\t\t\t}\n\t\t};\n\t\tconst capturedFinalizer = visible?.finalizeContent?.bind(visible);\n\t\tconst finalizerFor = () => collapsed && !signal.aborted ? void 0 : capturedFinalizer;\n\t\ttry {\n\t\t\tconst detached = snapshotJsonValue(exec.arguments);\n\t\t\tif (detached === void 0) throw new TypeError(\"tool execution arguments must be losslessly JSON-serializable\");\n\t\t\tconst execution = {\n\t\t\t\t...base,\n\t\t\t\targuments: deepFreeze(detached)\n\t\t\t};\n\t\t\tthis.deferredContexts.set(execution, deferredContexts);\n\t\t\tthis.contentFinalizers.set(execution, finalizerFor());\n\t\t\tthis.cancellationStates.set(execution, {\n\t\t\t\tcallerSignal: signal,\n\t\t\t\tbodyInvoked: false\n\t\t\t});\n\t\t\tif (collapsed) {\n\t\t\t\tif (signal.aborted) return {\n\t\t\t\t\tkind: \"final-result\",\n\t\t\t\t\texec: execution,\n\t\t\t\t\tresult: toolAbortedBeforeDispatchResult()\n\t\t\t\t};\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"final-result\",\n\t\t\t\t\texec: execution,\n\t\t\t\t\tresult: toolErrorResult(new ToolNotFoundError(name, `only \\`${RUN_CODE_NAME}\\` is callable directly — call \\`${name}\\` from inside a \\`${RUN_CODE_NAME}\\` program instead`))\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkind: \"ready\",\n\t\t\t\texec: execution\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconst execution = {\n\t\t\t\t...base,\n\t\t\t\targuments: void 0\n\t\t\t};\n\t\t\tthis.contentFinalizers.set(execution, finalizerFor());\n\t\t\treturn {\n\t\t\t\tkind: \"final-result\",\n\t\t\t\texec: execution,\n\t\t\t\tresult: toolErrorResult(error)\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Run the ordered pre-execute and monotonic guard stages for the scheduler.\n\t* @param input - the caller-supplied execution input.\n\t* @returns the prepared execution plus the next scheduler stage.\n\t* @internal\n\t*/\n\tasync prepareScheduledExecution(input) {\n\t\treturn this.prepareExecution(input, (prepared) => prepared);\n\t}\n\tasync prepareExecution(input, next) {\n\t\tconst created = this.createExecution(input);\n\t\tif (created.kind !== \"ready\") return next(created);\n\t\tconst exec = created.exec;\n\t\tif (this.callerCancelled(exec)) return next({\n\t\t\tkind: \"final-result\",\n\t\t\texec,\n\t\t\tresult: toolAbortedBeforeDispatchResult()\n\t\t});\n\t\ttry {\n\t\t\tconst carrier = scopeTarget(this, exec.agent);\n\t\t\tconst gate = await this.ctx.waterfall(carrier, \"tools/pre-execute\", exec, () => Promise.resolve({ kind: \"allow\" }));\n\t\t\tconst askResolution = gate.kind === \"ask\" ? await this.serviceAsk(exec, gate) : {\n\t\t\t\tdecision: gate,\n\t\t\t\tapprovalCancelled: false\n\t\t\t};\n\t\t\tconst { decision } = askResolution;\n\t\t\tif (this.callerCancelled(exec) && askResolution.approvalCancelled) return await next({\n\t\t\t\tkind: \"post-result\",\n\t\t\t\texec,\n\t\t\t\tresult: toolAbortedBeforeDispatchResult()\n\t\t\t});\n\t\t\tconst denialReason = decision.kind === \"allow\" ? this.guardReason(exec) : decision.reason;\n\t\t\tif (denialReason !== void 0) return await next({\n\t\t\t\tkind: \"post-result\",\n\t\t\t\texec,\n\t\t\t\tresult: this.materializeFinalResult({\n\t\t\t\t\tcontent: [{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Error: ${denialReason}`\n\t\t\t\t\t}],\n\t\t\t\t\tisError: true,\n\t\t\t\t\terror: { message: denialReason }\n\t\t\t\t})\n\t\t\t});\n\t\t\tif (this.callerCancelled(exec)) return await next({\n\t\t\t\tkind: \"post-result\",\n\t\t\t\texec,\n\t\t\t\tresult: toolAbortedBeforeDispatchResult()\n\t\t\t});\n\t\t\treturn await next({\n\t\t\t\tkind: \"dispatch\",\n\t\t\t\texec\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn next({\n\t\t\t\tkind: \"final-result\",\n\t\t\t\texec,\n\t\t\t\tresult: toolErrorResult(error)\n\t\t\t});\n\t\t}\n\t}\n\t/** Whether the original caller signal is currently aborted. */\n\tcallerCancelled(exec) {\n\t\tconst state = this.cancellationStates.get(exec);\n\t\t/* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */\n\t\tif (state === void 0) throw new Error(\"tool registry scheduler invariant violated: missing cancellation state\");\n\t\treturn state.callerSignal.aborted;\n\t}\n\t/** Canonical cancellation outcome selected by whether the tool body started. */\n\tcancellationResult(exec, prior) {\n\t\tconst state = this.cancellationStates.get(exec);\n\t\t/* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */\n\t\tif (state === void 0) throw new Error(\"tool registry scheduler invariant violated: missing cancellation state\");\n\t\treturn state.bodyInvoked ? toolAbortedResult(prior) : toolAbortedBeforeDispatchResult(prior);\n\t}\n\t/**\n\t* Dispatch the registered body with the original caller signal fused back\n\t* into any around-wrapper replacement. Cancellation never abandons the body:\n\t* a started promise reaches quiescence before its outcome becomes `ABORTED`.\n\t*/\n\tasync dispatchToolBody(exec) {\n\t\tconst state = this.cancellationStates.get(exec);\n\t\t/* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */\n\t\tif (state === void 0) throw new Error(\"tool registry scheduler invariant violated: missing cancellation state\");\n\t\tconst wrapperSignal = exec.signal;\n\t\tconst fused = fuseToolSignals(state.callerSignal, wrapperSignal);\n\t\tconst signal = fused.signal;\n\t\tif (isAborted(signal)) {\n\t\t\tfused.dispose();\n\t\t\treturn toolAbortedBeforeDispatchResult();\n\t\t}\n\t\texec.signal = signal;\n\t\ttry {\n\t\t\tconst tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== void 0);\n\t\t\tif (!tool) throw new ToolNotFoundError(exec.name);\n\t\t\tstate.bodyInvoked = true;\n\t\t\tconst returned = await tool.execute(exec.arguments, exec);\n\t\t\tconst result = this.createSuccessResult(exec, tool, returned);\n\t\t\treturn isAborted(signal) ? toolAbortedResult(result) : result;\n\t\t} catch (error) {\n\t\t\treturn toolErrorResult(error);\n\t\t} finally {\n\t\t\tfused.dispose();\n\t\t\texec.signal = wrapperSignal;\n\t\t}\n\t}\n\t/**\n\t* Run around-dispatch and the tool body. Tool and unknown-tool failures still\n\t* receive post-execute; pipeline failures are already final.\n\t* @param exec - the prepared execution.\n\t* @returns whether the result still needs post-execute.\n\t* @internal\n\t*/\n\tasync dispatchScheduledExecution(exec) {\n\t\ttry {\n\t\t\tconst mutableExec = exec;\n\t\t\tconst carrier = scopeTarget(this, exec.agent);\n\t\t\tconst result = await this.ctx.waterfall(carrier, \"tools/execute\", mutableExec, () => this.dispatchToolBody(mutableExec));\n\t\t\tconst normalized = this.normalizeDispatchResult(exec, result);\n\t\t\tconst deferredContexts = this.deferredContexts.get(exec);\n\t\t\t/* v8 ignore next -- dispatch only receives executions minted by this registry's prepare stage */\n\t\t\tif (deferredContexts === void 0) throw new Error(\"tool registry scheduler invariant violated: unprepared execution\");\n\t\t\tconst resultWithDeferredContexts = deferredContexts.length === 0 ? normalized : this.markCanonical(exec, {\n\t\t\t\t...normalized,\n\t\t\t\tadditionalContexts: [...deferredContexts, ...normalized.additionalContexts ?? []]\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tkind: \"post-result\",\n\t\t\t\tresult: this.callerCancelled(exec) && !resultWithDeferredContexts.isError ? this.cancellationResult(exec, resultWithDeferredContexts) : resultWithDeferredContexts\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tkind: \"final-result\",\n\t\t\t\tresult: toolErrorResult(error)\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Run ordered post-execute, then apply definition-owned content finalization,\n\t* materialize, and notify the final outcome.\n\t* @param exec - the prepared execution.\n\t* @param result - dispatch/pre result that still needs post-execute.\n\t* @returns the materialized final result.\n\t* @internal\n\t*/\n\tasync finalizeScheduledExecution(exec, result) {\n\t\ttry {\n\t\t\tconst postResult = await this.postExecute(exec, result);\n\t\t\treturn this.finishScheduledExecution(exec, this.callerCancelled(exec) && !postResult.isError ? this.cancellationResult(exec, postResult) : postResult);\n\t\t} catch (error) {\n\t\t\treturn this.finishScheduledExecution(exec, toolErrorResult(error));\n\t\t}\n\t}\n\t/**\n\t* Materialize the candidate, apply definition-owned content finalization,\n\t* then materialize and notify the authoritative result.\n\t* @param exec - the prepared execution.\n\t* @param result - final result.\n\t* @returns the materialized final result.\n\t* @internal\n\t*/\n\tfinishScheduledExecution(exec, result) {\n\t\tlet materializedResult;\n\t\ttry {\n\t\t\tmaterializedResult = this.materializeFinalResult(result);\n\t\t} catch (error) {\n\t\t\tmaterializedResult = this.materializeFinalResult(toolErrorResult(error));\n\t\t}\n\t\tlet finalResult;\n\t\ttry {\n\t\t\tfinalResult = this.materializeFinalResult(this.applyFinalContent(exec, materializedResult));\n\t\t} catch (error) {\n\t\t\tfinalResult = this.materializeFinalResult(toolErrorResult(error));\n\t\t}\n\t\tthis.notifyResult(exec, finalResult);\n\t\treturn finalResult;\n\t}\n\t/** Apply the snapshotted tool-owned content transform without exposing other result fields. */\n\tapplyFinalContent(exec, result) {\n\t\tconst finalizeContent = this.contentFinalizers.get(exec);\n\t\tif (finalizeContent === void 0) return result;\n\t\tconst content = finalizeContent(exec, result);\n\t\treturn content === void 0 ? result : {\n\t\t\t...result,\n\t\t\tcontent\n\t\t};\n\t}\n\t/** Notify observers without exposing a mutation or error channel into the outcome. */\n\tnotifyResult(exec, result) {\n\t\tObject.freeze(exec);\n\t\tconst { name: toolName, callId } = exec;\n\t\tconst reportFailure = (error) => {\n\t\t\tthis.ctx.logger.warn(`tool \"${toolName}\" (${callId}): tools/result observer failed: ${errorMessage(error)}`);\n\t\t};\n\t\tconst callbacks = this.ctx.events.dispatch(\"emit\", [\n\t\t\tscopeTarget(this, exec.agent),\n\t\t\t\"tools/result\",\n\t\t\texec,\n\t\t\tresult\n\t\t]);\n\t\tfor (const callback of callbacks) try {\n\t\t\tconst returned = callback(exec, result);\n\t\t\tPromise.resolve(returned).catch(reportFailure);\n\t\t} catch (error) {\n\t\t\treportFailure(error);\n\t\t}\n\t}\n\t/**\n\t* Resolve an `ask` decision to allow/deny through the approval seam. The\n\t* seam is consumed opportunistically with `ctx.get('approval')` — a\n\t* deployment that composes no ApprovalService keeps the historical degrade\n\t* to deny, and an unmount mid-session degrades the same way on the next ask.\n\t* An agent-less execution also degrades: without an agent there is no\n\t* session to audit to and no UI to route to. Otherwise the outcome maps\n\t* one-to-one — `allowed-once` proceeds; the three non-grants deny with\n\t* distinct reasons so the model can tell a human \"no\" from an absent\n\t* approval channel.\n\t*/\n\tasync serviceAsk(exec, ask) {\n\t\tconst approval = this.ctx.get(\"approval\");\n\t\tif (approval === void 0) return {\n\t\t\tdecision: {\n\t\t\t\tkind: \"deny\",\n\t\t\t\treason: ask.reason ?? `tool \"${exec.name}\" requires approval (not yet supported)`\n\t\t\t},\n\t\t\tapprovalCancelled: false\n\t\t};\n\t\tif (exec.agent === void 0) return {\n\t\t\tdecision: {\n\t\t\t\tkind: \"deny\",\n\t\t\t\treason: `tool \"${exec.name}\" requires approval, but the call has no agent to route it through`\n\t\t\t},\n\t\t\tapprovalCancelled: false\n\t\t};\n\t\tconst outcome = await approval.request({\n\t\t\tagent: exec.agent,\n\t\t\ttoolName: exec.name,\n\t\t\tcallId: exec.callId,\n\t\t\t...ask.reason !== void 0 ? { reason: ask.reason } : {},\n\t\t\tsignal: exec.signal\n\t\t});\n\t\tswitch (outcome) {\n\t\t\tcase \"allowed-once\": return {\n\t\t\t\tdecision: { kind: \"allow\" },\n\t\t\t\tapprovalCancelled: false\n\t\t\t};\n\t\t\tcase \"rejected\": return {\n\t\t\t\tdecision: {\n\t\t\t\t\tkind: \"deny\",\n\t\t\t\t\treason: `the user rejected tool \"${exec.name}\"`\n\t\t\t\t},\n\t\t\t\tapprovalCancelled: false\n\t\t\t};\n\t\t\tcase \"cancelled\": return {\n\t\t\t\tdecision: {\n\t\t\t\t\tkind: \"deny\",\n\t\t\t\t\treason: `approval for tool \"${exec.name}\" was cancelled`\n\t\t\t\t},\n\t\t\t\tapprovalCancelled: true\n\t\t\t};\n\t\t\tcase \"unavailable\": return {\n\t\t\t\tdecision: {\n\t\t\t\t\tkind: \"deny\",\n\t\t\t\t\treason: `tool \"${exec.name}\" requires approval, but no approval channel is available`\n\t\t\t\t},\n\t\t\t\tapprovalCancelled: false\n\t\t\t};\n\t\t\tdefault: return assertNever(outcome, \"ApprovalOutcome\");\n\t\t}\n\t}\n\t/**\n\t* Run the `tools/post-execute` waterfall over a dispatched `result` and apply\n\t* its {@link PostToolDecision}: `accept` keeps the call successful (replacing\n\t* `content` when given), `block` turns it into an `isError` whose content is\n\t* the corrective `feedback`. Either decision may attach `additionalContexts`,\n\t* which are ferried on the returned result for the loop's active-batch FIFO.\n\t* Context deferred by the tool body survives an accepted result but is\n\t* discarded when the outer call is blocked; a block exposes only context the\n\t* blocking decision explicitly supplied.\n\t* Runs inside `execute`'s outer try/catch (a throwing listener → isError).\n\t*/\n\tasync postExecute(exec, result) {\n\t\tconst decision = await this.ctx.waterfall(scopeTarget(this, exec.agent), \"tools/post-execute\", exec, result, () => Promise.resolve({ kind: \"accept\" }));\n\t\tconst decisionContexts = decision.additionalContexts ?? [];\n\t\tif (decision.kind === \"block\") {\n\t\t\tconst message = failureMessageFromContent(decision.feedback);\n\t\t\treturn this.markCanonical(exec, {\n\t\t\t\tcontent: decision.feedback,\n\t\t\t\tisError: true,\n\t\t\t\terror: { message },\n\t\t\t\t...decisionContexts.length > 0 ? { additionalContexts: decisionContexts } : {}\n\t\t\t});\n\t\t}\n\t\tif (Object.hasOwn(decision, \"content\") && Object.hasOwn(decision, \"value\")) throw new TypeError(\"tools/post-execute accept decision cannot replace both value and content\");\n\t\tconst additionalContexts = [...result.additionalContexts ?? [], ...decisionContexts];\n\t\tif (Object.hasOwn(decision, \"value\")) {\n\t\t\tif (result.isError) throw new TypeError(\"tools/post-execute cannot replace the value of a failed result\");\n\t\t\tconst tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== void 0);\n\t\t\tif (tool === void 0) throw new ToolNotFoundError(exec.name);\n\t\t\tconst replaced = this.createSuccessResult(exec, tool, decision.value);\n\t\t\treturn this.markCanonical(exec, {\n\t\t\t\t...replaced,\n\t\t\t\t...additionalContexts.length > 0 ? { additionalContexts } : {}\n\t\t\t});\n\t\t}\n\t\treturn this.markCanonical(exec, {\n\t\t\t...result,\n\t\t\t...decision.content !== void 0 ? { content: decision.content } : {},\n\t\t\t...additionalContexts.length > 0 ? { additionalContexts } : {}\n\t\t});\n\t}\n\t/** Registry-normalized results and the exact dispatch that validated each value. */\n\tcanonicalResults = /* @__PURE__ */ new WeakMap();\n\t/** Mark one registry-normalized result as canonical only for its owning dispatch. */\n\tmarkCanonical(exec, result) {\n\t\tthis.canonicalResults.set(result, exec.token);\n\t\treturn result;\n\t}\n\t/** Snapshot, validate, render, and optionally project one successful body value. */\n\tcreateSuccessResult(exec, tool, candidate) {\n\t\tconst detached = snapshotToolValue(tool.name, candidate);\n\t\tconst violations = validateJsonSchemaValue(tool.output.schema, detached, \"value\");\n\t\tif (violations.length > 0) throw new ToolOutputError(tool.name, violations);\n\t\tconst value = deepFreeze(detached);\n\t\tlet rendered;\n\t\ttry {\n\t\t\trendered = tool.output.render(exec.arguments, value);\n\t\t} catch (error) {\n\t\t\tthrow projectionError(tool.name, \"render\", error);\n\t\t}\n\t\tconst content = snapshotProjection(tool.name, \"render\", rendered);\n\t\tlet meta;\n\t\tif (exec.parent === void 0 && tool.output.presentationMeta !== void 0) {\n\t\t\tlet projected;\n\t\t\ttry {\n\t\t\t\tprojected = tool.output.presentationMeta(exec.arguments, value);\n\t\t\t} catch (error) {\n\t\t\t\tthrow projectionError(tool.name, \"presentationMeta\", error);\n\t\t\t}\n\t\t\tmeta = snapshotProjection(tool.name, \"presentationMeta\", projected);\n\t\t}\n\t\tconst concludesTurn = this.concludingExecutions.has(exec);\n\t\treturn this.markCanonical(exec, this.materializeFinalResult({\n\t\t\tisError: false,\n\t\t\tvalue,\n\t\t\tcontent,\n\t\t\t...meta !== void 0 ? { meta } : {},\n\t\t\t...concludesTurn ? { concludesTurn: true } : {}\n\t\t}));\n\t}\n\t/** Normalize an around-dispatch wrapper's authored result through the owning output contract. */\n\tnormalizeDispatchResult(exec, result) {\n\t\tif (this.canonicalResults.get(result) === exec.token) return result;\n\t\tif (result.isError) return this.markCanonical(exec, {\n\t\t\tisError: true,\n\t\t\terror: result.error,\n\t\t\tcontent: result.content,\n\t\t\t...result.meta !== void 0 ? { meta: result.meta } : {},\n\t\t\t...result.additionalContexts !== void 0 ? { additionalContexts: result.additionalContexts } : {}\n\t\t});\n\t\tconst tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== void 0);\n\t\tif (tool === void 0) throw new ToolNotFoundError(exec.name);\n\t\tconst normalized = this.createSuccessResult(exec, tool, result.value);\n\t\treturn this.markCanonical(exec, {\n\t\t\t...normalized,\n\t\t\t...result.additionalContexts !== void 0 ? { additionalContexts: result.additionalContexts } : {}\n\t\t});\n\t}\n\t/** Materialize the authoritative commit outcome once, immediately before `tools/result`. */\n\tmaterializeFinalResult(result) {\n\t\tconst presentation = {\n\t\t\tcontent: result.content,\n\t\t\t...result.meta !== void 0 ? { meta: result.meta } : {},\n\t\t\t...result.additionalContexts !== void 0 ? { additionalContexts: result.additionalContexts } : {}\n\t\t};\n\t\tif (result.isError) return materializePresentation({\n\t\t\tisError: true,\n\t\t\terror: result.error,\n\t\t\t...presentation\n\t\t});\n\t\treturn deepFreeze({\n\t\t\t...materializePresentation({\n\t\t\t\tisError: false,\n\t\t\t\t...presentation,\n\t\t\t\t...result.concludesTurn === true ? { concludesTurn: true } : {}\n\t\t\t}),\n\t\t\tvalue: result.value\n\t\t});\n\t}\n};\n/** Mint a same-process correlation token whose identity is its value. */\nfunction createExecutionToken() {\n\treturn Symbol(\"dsh.tool.execution\");\n}\nfunction toolErrorResult(error) {\n\tconst info = errorInfo(error);\n\tconst message = errorMessage(error);\n\treturn {\n\t\tcontent: [{\n\t\t\ttype: \"text\",\n\t\t\ttext: `Error: ${message}`\n\t\t}],\n\t\tisError: true,\n\t\terror: {\n\t\t\tmessage,\n\t\t\t...info ? { info } : {}\n\t\t}\n\t};\n}\n/** Read live abort state across an await without treating it as synchronously immutable. */\nfunction isAborted(signal) {\n\treturn signal.aborted;\n}\n/**\n* Fuse caller and wrapper cancellation without nesting `AbortSignal.any`.\n* Keeping the relay dispatch-scoped also removes listeners when work settles.\n*/\nfunction fuseToolSignals(caller, wrapper) {\n\tif (caller === wrapper) return {\n\t\tsignal: caller,\n\t\tdispose() {}\n\t};\n\tconst controller = new AbortController();\n\tlet listening = false;\n\tconst dispose = () => {\n\t\tif (!listening) return;\n\t\tlistening = false;\n\t\tcaller.removeEventListener(\"abort\", abortFromCaller);\n\t\twrapper.removeEventListener(\"abort\", abortFromWrapper);\n\t};\n\tconst abortFrom = (source) => {\n\t\tconst reason = source.reason;\n\t\tcontroller.abort(reason);\n\t\tdispose();\n\t};\n\tconst abortFromCaller = () => {\n\t\tabortFrom(caller);\n\t};\n\tconst abortFromWrapper = () => {\n\t\tabortFrom(wrapper);\n\t};\n\tif (wrapper.aborted) abortFromWrapper();\n\telse if (caller.aborted) abortFromCaller();\n\telse {\n\t\tlistening = true;\n\t\tcaller.addEventListener(\"abort\", abortFromCaller, { once: true });\n\t\twrapper.addEventListener(\"abort\", abortFromWrapper, { once: true });\n\t}\n\treturn {\n\t\tsignal: controller.signal,\n\t\tdispose\n\t};\n}\n/** Canonical result when cancellation supersedes success after body invocation. */\nfunction toolAbortedResult(prior) {\n\tconst additionalContexts = prior?.additionalContexts ?? [];\n\treturn {\n\t\tcontent: [{\n\t\t\ttype: \"text\",\n\t\t\ttext: \"Error: tool call aborted\"\n\t\t}],\n\t\tisError: true,\n\t\terror: {\n\t\t\tmessage: \"tool call aborted\",\n\t\t\tinfo: {\n\t\t\t\tname: \"AbortError\",\n\t\t\t\tcode: TOOL_ABORTED\n\t\t\t}\n\t\t},\n\t\t...additionalContexts.length > 0 ? { additionalContexts } : {}\n\t};\n}\n/** Canonical result when cancellation prevents tool body invocation. */\nfunction toolAbortedBeforeDispatchResult(prior) {\n\tconst additionalContexts = prior?.additionalContexts ?? [];\n\treturn {\n\t\tcontent: [{\n\t\t\ttype: \"text\",\n\t\t\ttext: \"Error: tool call aborted before dispatch\"\n\t\t}],\n\t\tisError: true,\n\t\terror: {\n\t\t\tmessage: \"tool call aborted before dispatch\",\n\t\t\tinfo: {\n\t\t\t\tname: \"AbortError\",\n\t\t\t\tcode: TOOL_ABORTED_BEFORE_DISPATCH\n\t\t\t}\n\t\t},\n\t\t...additionalContexts.length > 0 ? { additionalContexts } : {}\n\t};\n}\n//#endregion\nexport { CodeRunFailedError, JsonSchemaError, RUN_CODE_NAME, TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH, TOOL_RUNTIME_SCHEDULER, ToolArgsError, ToolNotFoundError, ToolOutputError, ToolRuntime, ToolRuntime as default, assertObjectJsonSchema, assertSupportedJsonSchema, defineContentToolFixture, defineTool, jsonSchemaToPy, jsonSchemaToTs, parameterSchemaSpecToJsonSchema, renderToolsSdk, renderToolsSdkPy, validateArgs, validateJsonSchemaValue, valueSchemaSpecToJsonSchema };\n","var _a;\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // Use a relative epsilon scaled to the magnitude of the result\n const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function`\n // as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).\n// Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;\n rest.path ?? (rest.path = []);\n rest.message = message;\n if (ctx?.reportInput) {\n rest.input = _input;\n }\n return rest;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = []) {\n this.content = [];\n this.indent = 0;\n if (this)\n this.args = args;\n }\n indented(fn) {\n this.indent += 1;\n fn(this);\n this.indent -= 1;\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const args = this?.args;\n const content = this?.content ?? [``];\n const lines = [...content.map((x) => ` ${x}`)];\n // console.log(lines.join(\"\\n\"));\n return new F(...args, lines.join(\"\\n\"));\n }\n}\n","export const version = {\n major: 4,\n minor: 4,\n patch: 3,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary\n // initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n }));\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n // When normalize is off, require :// for http/https URLs\n // This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source) {\n if (!/^https?:\\/\\//i.test(trimmed)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n }\n // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv4`;\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {\n const isPresent = key in input;\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (isOptionalIn && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && !isOptionalIn) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalIn = _catchall.optin === \"optional\";\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n // skip __proto__ so it can't replace the result prototype via the\n // assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n // const sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalIn = el._zod.optin === \"optional\";\n const isOptionalOut = el._zod.optout === \"optional\";\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalIn = schema?._zod?.optin === \"optional\";\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${k} in input;\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n }\n\n if (${id}_present) {\n if (${id}.value === undefined) {\n newResult[${k}] = undefined;\n } else {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators\n // have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed\n // array. The post-processing in `handleTupleResults` walks them in\n // order so it can decide whether an absent optional-output error can\n // truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n }\n }\n if (def.rest) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n if (items[i]._zod[key] !== \"optional\")\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional\n // rule, but only after `optoutStart`: the first index where the output\n // tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)\n // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n payload.fallback = true;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (input === undefined && (result.issues.length || result.fallback)) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const input = payload.value;\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, input));\n return handleOptionalResult(result, input);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n if (left.issues.length) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._def = def;\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n return function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n };\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this\n // lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance,\n // preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n external: params?.external ?? undefined,\n };\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n process(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n Object.assign(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema\n // or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n // biome-ignore lint:\n continue;\n }\n }\n }\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n Object.assign(schema, refSchema);\n }\n // restore child's own properties (child wins)\n Object.assign(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema\n // This handles cases like: readonly().meta({id}).describe()\n // where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n Object.assign(result, root.def ?? root.schema);\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract\n // schemas into $defs — it is not user-facing JSON Schema metadata. Strip it\n // from the output body where it would otherwise leak. The id is preserved\n // implicitly via the $defs key (and via $ref paths).\n const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n if (rootMetaId !== undefined && result.id === rootMetaId)\n delete result.id;\n // build defs object\n const defs = ctx.external?.defs ?? {};\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n if (seen.def.id === seen.defId)\n delete seen.def.id;\n defs[seen.defId] = seen.def;\n }\n }\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed\n // each call to finalize() is functionally independent\n // though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n if (_schema._zod.traits.has(\"$ZodCodec\"))\n return true;\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // JSON Schema format: \"time\" requires a full time with offset or Z\n // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n if (format === \"time\") {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n json.allOf = [\n ...regexes.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n if (exMin) {\n if (legacy) {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n else if (typeof minimum === \"number\") {\n json.minimum = minimum;\n }\n if (exMax) {\n if (legacy) {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n else if (typeof maximum === \"number\") {\n json.maximum = maximum;\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, _params) => {\n const def = schema._zod.def;\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Function types cannot be represented in JSON Schema\");\n }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = process(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape;\n for (const key in shape) {\n json.properties[key] = process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (ctx.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(requiredKeys);\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = process(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)\n // This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (rest) {\n json.items = rest;\n }\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n json.minItems = prefixItems.length;\n if (!rest) {\n json.maxItems = prefixItems.length;\n }\n }\n else {\n json.items = prefixItems;\n if (rest) {\n json.additionalItems = rest;\n }\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties\n // This correctly represents \"only validate keys matching the pattern\" semantics\n // and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n json.patternProperties[pattern.source] = valueSchema;\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n }\n json.additionalProperties = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n if (keyValues) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues;\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io === \"input\")\n json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n process(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n schemas[key] = finalize(ctx, schema);\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\n// Lazy-bind builder methods.\n//\n// Builder methods (`.optional`, `.array`, `.refine`, ...) live as\n// non-enumerable getters on each concrete schema constructor's\n// prototype. On first access from an instance the getter allocates\n// `fn.bind(this)` and caches it as an own property on that instance,\n// so detached usage (`const m = schema.optional; m()`) still works\n// and the per-instance allocation only happens for methods actually\n// touched.\n//\n// One install per (prototype, group), memoized by `_installedGroups`.\nconst _installedGroups = /* @__PURE__ */ new WeakMap();\nfunction _installLazyMethods(inst, group, methods) {\n const proto = Object.getPrototypeOf(inst);\n let installed = _installedGroups.get(proto);\n if (!installed) {\n installed = new Set();\n _installedGroups.set(proto, installed);\n }\n if (installed.has(group))\n return;\n installed.add(group);\n for (const key in methods) {\n const fn = methods[key];\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const bound = fn.bind(this);\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable: true,\n value: bound,\n });\n return bound;\n },\n set(v) {\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable: true,\n value: v,\n });\n },\n });\n }\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n core.$ZodType.init(inst, def);\n Object.assign(inst[\"~standard\"], {\n jsonSchema: {\n input: createStandardJSONSchemaMethod(inst, \"input\"),\n output: createStandardJSONSchemaMethod(inst, \"output\"),\n },\n });\n inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n inst.def = def;\n inst.type = def.type;\n Object.defineProperty(inst, \"_def\", { value: def });\n // Parse-family is intentionally kept as per-instance closures: these are\n // the hot path AND the most-detached methods (`arr.map(schema.parse)`,\n // `const { parse } = schema`, etc.). Eager closures here mean callers pay\n // ~12 closure allocations per schema but get monomorphic call sites and\n // detached usage that \"just works\".\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.spa = inst.safeParseAsync;\n inst.encode = (data, params) => parse.encode(inst, data, params);\n inst.decode = (data, params) => parse.decode(inst, data, params);\n inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n // All builder methods are placed on the internal prototype as lazy-bind\n // getters. On first access per-instance, a bound thunk is allocated and\n // cached as an own property; subsequent accesses skip the getter. This\n // means: no per-instance allocation for unused methods, full\n // detachability preserved (`const m = schema.optional; m()` works), and\n // shared underlying function references across all instances.\n _installLazyMethods(inst, \"ZodType\", {\n check(...chks) {\n const def = this.def;\n return this.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), { parent: true });\n },\n with(...chks) {\n return this.check(...chks);\n },\n clone(def, params) {\n return core.clone(this, def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n refine(check, params) {\n return this.check(refine(check, params));\n },\n superRefine(refinement, params) {\n return this.check(superRefine(refinement, params));\n },\n overwrite(fn) {\n return this.check(checks.overwrite(fn));\n },\n optional() {\n return optional(this);\n },\n exactOptional() {\n return exactOptional(this);\n },\n nullable() {\n return nullable(this);\n },\n nullish() {\n return optional(nullable(this));\n },\n nonoptional(params) {\n return nonoptional(this, params);\n },\n array() {\n return array(this);\n },\n or(arg) {\n return union([this, arg]);\n },\n and(arg) {\n return intersection(this, arg);\n },\n transform(tx) {\n return pipe(this, transform(tx));\n },\n default(d) {\n return _default(this, d);\n },\n prefault(d) {\n return prefault(this, d);\n },\n catch(params) {\n return _catch(this, params);\n },\n pipe(target) {\n return pipe(this, target);\n },\n readonly() {\n return readonly(this);\n },\n describe(description) {\n const cl = this.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n },\n meta(...args) {\n // overloaded: meta() returns the registered metadata, meta(data)\n // returns a clone with `data` registered. The mapped type picks\n // up the second overload, so we accept variadic any-args and\n // return `any` to satisfy both at runtime.\n if (args.length === 0)\n return core.globalRegistry.get(this);\n const cl = this.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n },\n isOptional() {\n return this.safeParse(undefined).success;\n },\n isNullable() {\n return this.safeParse(null).success;\n },\n apply(fn) {\n return fn(this);\n },\n });\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n return inst;\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n _installLazyMethods(inst, \"_ZodString\", {\n regex(...args) {\n return this.check(checks.regex(...args));\n },\n includes(...args) {\n return this.check(checks.includes(...args));\n },\n startsWith(...args) {\n return this.check(checks.startsWith(...args));\n },\n endsWith(...args) {\n return this.check(checks.endsWith(...args));\n },\n min(...args) {\n return this.check(checks.minLength(...args));\n },\n max(...args) {\n return this.check(checks.maxLength(...args));\n },\n length(...args) {\n return this.check(checks.length(...args));\n },\n nonempty(...args) {\n return this.check(checks.minLength(1, ...args));\n },\n lowercase(params) {\n return this.check(checks.lowercase(params));\n },\n uppercase(params) {\n return this.check(checks.uppercase(params));\n },\n trim() {\n return this.check(checks.trim());\n },\n normalize(...args) {\n return this.check(checks.normalize(...args));\n },\n toLowerCase() {\n return this.check(checks.toLowerCase());\n },\n toUpperCase() {\n return this.check(checks.toUpperCase());\n },\n slugify() {\n return this.check(checks.slugify());\n },\n });\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n inst.email = (params) => inst.check(core._email(ZodEmail, params));\n inst.url = (params) => inst.check(core._url(ZodURL, params));\n inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n // iso\n inst.datetime = (params) => inst.check(iso.datetime(params));\n inst.date = (params) => inst.check(iso.date(params));\n inst.time = (params) => inst.check(iso.time(params));\n inst.duration = (params) => inst.check(iso.duration(params));\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: core.regexes.httpProtocol,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n _installLazyMethods(inst, \"ZodNumber\", {\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n int(params) {\n return this.check(int(params));\n },\n safe(params) {\n return this.check(int(params));\n },\n positive(params) {\n return this.check(checks.gt(0, params));\n },\n nonnegative(params) {\n return this.check(checks.gte(0, params));\n },\n negative(params) {\n return this.check(checks.lt(0, params));\n },\n nonpositive(params) {\n return this.check(checks.lte(0, params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n step(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n finite() {\n return this;\n },\n });\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\n});\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\n});\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\n// int64\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\n// uint64\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n _installLazyMethods(inst, \"ZodArray\", {\n min(n, params) {\n return this.check(checks.minLength(n, params));\n },\n nonempty(params) {\n return this.check(checks.minLength(1, params));\n },\n max(n, params) {\n return this.check(checks.maxLength(n, params));\n },\n length(n, params) {\n return this.check(checks.length(n, params));\n },\n unwrap() {\n return this.element;\n },\n });\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.defineLazy(inst, \"shape\", () => {\n return def.shape;\n });\n _installLazyMethods(inst, \"ZodObject\", {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n return this.clone({ ...this._zod.def, catchall: catchall });\n },\n passthrough() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n loose() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n strict() {\n return this.clone({ ...this._zod.def, catchall: never() });\n },\n strip() {\n return this.clone({ ...this._zod.def, catchall: undefined });\n },\n extend(incoming) {\n return util.extend(this, incoming);\n },\n safeExtend(incoming) {\n return util.safeExtend(this, incoming);\n },\n merge(other) {\n return util.merge(this, other);\n },\n pick(mask) {\n return util.pick(this, mask);\n },\n omit(mask) {\n return util.omit(this, mask);\n },\n partial(...args) {\n return util.partial(ZodOptional, this, args[0]);\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\n },\n });\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n inst.rest = (rest) => inst.clone({\n ...inst._zod.def,\n rest: rest,\n });\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n inst.options = Object.values(def.entries);\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n payload.value = output;\n payload.fallback = true;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodCustom({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n return new ZodPreprocess({\n type: \"pipe\",\n in: transform(fn),\n out: schema,\n });\n}\n","import { Service } from \"@deepseek-ai/cordis\";\nimport { scopeTarget } from \"@deepseek-ai/dsh-scope\";\nimport { assertObjectJsonSchema } from \"@deepseek-ai/dsh-tools\";\nimport { HarnessError, boundContextSummary, createUserMessage, errorChain } from \"@deepseek-ai/dsh-llm\";\nimport { randomUUID } from \"node:crypto\";\nimport { foldConsumedWork } from \"@deepseek-ai/dsh-agent\";\nimport { Session, SessionId, snapshotJsonValue } from \"@deepseek-ai/dsh-session\";\nimport { z } from \"zod\";\nimport { accessSync, constants, statSync } from \"node:fs\";\nimport { isAbsolute, resolve } from \"node:path\";\n//#region lib/types/error.js\n/**\n* Typed failures shared by subagent service and provider operations.\n*\n* @module @deepseek-ai/dsh-subagent\n*/\n/** Typed failure for the subagent seam. */\nvar SubagentError = class extends HarnessError {\n\tconstructor(message, code, options) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"SubagentError\";\n\t}\n};\n//#endregion\n//#region lib/types/depth.js\n/**\n* Delegation-depth accounting: the recursion budget a parent passes to its\n* children. Kept apart from the service so composition helpers can read it\n* without importing the registry.\n*\n* @module @deepseek-ai/dsh-subagent/depth\n*/\n/**\n* Read an agent's delegation depth, treating absence as top-level depth zero.\n* The persisted session header is authoritative and monotone: runtime\n* `AgentOptions.subagentDepth` may DEEPEN the count but can never lower it —\n* a resumed child arrives with fresh options, and counting it from zero would\n* let it delegate as if it were top-level.\n* @param agent - the agent whose header and options carry the depth.\n* @returns its non-negative safe-integer depth.\n* @throws if the runtime `AgentOptions.subagentDepth` is not a non-negative safe integer.\n*/\nfunction delegationDepthOf(agent) {\n\tconst runtime = agent.options.subagentDepth;\n\tif (runtime !== void 0 && (!Number.isSafeInteger(runtime) || runtime < 0 || Object.is(runtime, -0))) throw new TypeError(\"agent subagentDepth must be a non-negative safe integer\");\n\treturn Math.max(agent.session.header.delegationDepth ?? 0, runtime ?? 0);\n}\n/**\n* Reject a recursion cap that cannot represent an exact delegation depth.\n* @param maxDepth - the optional runtime value to validate.\n*/\nfunction assertSubagentMaxDepth(maxDepth) {\n\tif (maxDepth !== void 0 && (typeof maxDepth !== \"number\" || !Number.isSafeInteger(maxDepth) || maxDepth < 0 || Object.is(maxDepth, -0))) throw new TypeError(\"subagent maxDepth must be a non-negative safe integer\");\n}\n//#endregion\n//#region lib/types/assistant-output.js\n/**\n* Canonical selection of a child's final assistant output. Backend run results\n* and `subagent/end.lastAssistantMessage` apply the same rule: select the last\n* non-empty assistant message. An empty-content message records usage only\n* when the loop appends it after a max-tokens step with no executable blocks,\n* so it does not replace earlier output. If no non-empty message exists,\n* select the accumulated assistant text. Selection is independent of the\n* run's stop reason.\n*\n* @module @deepseek-ai/dsh-subagent/assistant-output\n*/\n/**\n* Incremental fold of the selection rule, for backends that observe a child's\n* output as it streams: session-event backends {@link push} each event, and\n* transports without session events (ACP content chunks) {@link pushText} raw\n* text into the same streamed fallback.\n*/\nvar AssistantOutputFold = class {\n\tmessage;\n\tpartial = [];\n\t/**\n\t* Fold one session event: a non-empty assistant message becomes the\n\t* candidate final answer, and a `text-delta` chunk extends the streamed\n\t* fallback; every other event contributes nothing.\n\t* @param event - the next observed session event.\n\t*/\n\tpush(event) {\n\t\tif (event.type === \"assistant/message\") {\n\t\t\tconst content = event.data.message.content;\n\t\t\tif (content.length > 0) this.message = content;\n\t\t} else if (event.type === \"assistant/chunk\" && event.data.chunk.type === \"text-delta\") this.pushText(event.data.chunk.text);\n\t}\n\t/**\n\t* Extend the streamed fallback with text observed outside session events.\n\t* @param text - the next streamed text piece (an empty piece is a no-op).\n\t*/\n\tpushText(text) {\n\t\tif (text.length > 0) this.partial.push(text);\n\t}\n\t/**\n\t* Select the final output folded so far.\n\t* @returns the last non-empty assistant message, else the accumulated\n\t* streamed text, or `undefined` when the child produced neither.\n\t*/\n\tcollect() {\n\t\tif (this.message !== void 0) return this.message;\n\t\tconst text = this.partial.join(\"\");\n\t\treturn text.length > 0 ? [{\n\t\t\ttype: \"text\",\n\t\t\ttext\n\t\t}] : void 0;\n\t}\n};\n/**\n* Apply the selection rule to one complete child-owned event suffix.\n* @param events - the child-owned events (after any seed or epoch boundary).\n* @returns the selected output, or `undefined` when the child produced none.\n*/\nfunction finalAssistantOutput(events) {\n\tconst fold = new AssistantOutputFold();\n\tfor (const event of events) fold.push(event);\n\treturn fold.collect();\n}\n//#endregion\n//#region lib/types/types.js\n/**\n* The seam's consumer-facing contracts: request, result, and capability types\n* for {@link SubagentProvider}, plus the `subagent/start` and `subagent/end`\n* payloads that plugins and hosts observe. Internal control interfaces belong\n* with their implementation — the lifecycle observer in `./lifecycle.ts`, the\n* continuation host in `./continuation.ts` — so this module stays the published\n* surface rather than a bag of everything type-shaped.\n*\n* @module @deepseek-ai/dsh-subagent/types\n*/\n/**\n* Brand a string as a {@link SubagentRunId}.\n* @param id - the raw run id.\n* @returns the same string, branded.\n*/\nfunction SubagentRunId(id) {\n\treturn id;\n}\n//#endregion\n//#region lib/types/lifecycle.js\n/**\n* Lifecycle-edge publication for both subagent shapes: the contained emitter,\n* the one-shot run observer, and the continuable Activation observer.\n*\n* The public payload contracts ({@link SubagentRunInfo},\n* {@link SubagentRunEndInfo}) live in `./types.ts` with the rest of the seam's\n* consumer-facing types; this module owns only the implementation and the\n* package-private {@link ActivationObserver} the continuation manager consumes.\n* Keeping the internal control interface out of the published surface is\n* deliberate: the observer's `start`/`capture`/`settle` ordering is a contract\n* between this module and one in-package caller, not something a plugin may\n* depend on.\n*\n* @module @deepseek-ai/dsh-subagent/lifecycle\n*/\n/**\n* Build the contained lifecycle emitter this seam publishes every edge through.\n* Every listener is independently contained: a synchronous throw or a rejected\n* returned promise is logged without starving peer listeners, changing the run,\n* or — for provider removal, which fires from a disposer — breaking teardown.\n* @param ctx - the service's own context, owning dispatch and the logger.\n* @param carrier - resolve the scoped dispatch carrier for one delegating parent.\n* @returns the emitter both observers and the provider registry publish through.\n*/\nfunction createLifecycleEmitter(ctx, carrier) {\n\treturn (name, info, parent) => {\n\t\tconst dispatchArgs = parent === void 0 ? [name, info] : [\n\t\t\tcarrier(parent),\n\t\t\tname,\n\t\t\tinfo\n\t\t];\n\t\tfor (const callback of ctx.events.dispatch(\"emit\", dispatchArgs)) try {\n\t\t\tconst returned = callback(info);\n\t\t\tPromise.resolve(returned).catch((error) => {\n\t\t\t\tctx.logger.warn(`subagent: ${name} listener rejected: ${renderThrown(error)}`);\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tctx.logger.warn(`subagent: ${name} listener threw: ${renderThrown(error)}`);\n\t\t}\n\t};\n}\n/**\n* Emit the start/end lifecycle pair for one accepted one-shot run.\n* @param emit - the contained lifecycle emitter.\n* @param provider - the provider that established the run.\n* @param parent - the delegating parent keying scoped dispatch.\n* @param run - the published run whose settlement closes the pair.\n* @returns the same run, unchanged.\n*/\nfunction observeRun(emit, provider, parent, run) {\n\tconst identity = {\n\t\trunId: SubagentRunId(randomUUID()),\n\t\tprovider,\n\t\tid: run.id,\n\t\tlocal: run.localAgent !== void 0\n\t};\n\trun.result.then((result) => {\n\t\temit(\"subagent/end\", {\n\t\t\t...identity,\n\t\t\tstopReason: result.stopReason,\n\t\t\t...result.output.length === 0 ? {} : { lastAssistantMessage: result.output }\n\t\t}, parent);\n\t}, () => {\n\t\temit(\"subagent/end\", {\n\t\t\t...identity,\n\t\t\tstopReason: \"error\"\n\t\t}, parent);\n\t});\n\temit(\"subagent/start\", identity, parent);\n\treturn run;\n}\n/**\n* Build the observer for one continuable Activation's residency epoch. Observers\n* see the same vocabulary as a one-shot run, so a child's start and settlement\n* remain observable without exposing whether the manager materialized, woke, or\n* cold-resumed it. Creation failure before residency emits no lifecycle edge.\n* @param emit - the contained lifecycle emitter.\n* @param provider - the provider name recorded in the durable descriptor.\n* @param childId - the durable child session id.\n* @param parent - the exact live direct parent keying scoped dispatch.\n* @returns the observer whose edges this epoch publishes.\n*/\nfunction createActivationObserver(emit, provider, childId, parent) {\n\tconst identity = {\n\t\trunId: SubagentRunId(randomUUID()),\n\t\tprovider,\n\t\tid: childId,\n\t\tlocal: true\n\t};\n\tlet boundary = 0;\n\tlet captured = { stopReason: \"completed\" };\n\tconst terminal = (failure) => failure === void 0 ? captured : { stopReason: \"error\" };\n\treturn {\n\t\tstart: (child) => {\n\t\t\tboundary = child.session.events.length;\n\t\t\temit(\"subagent/start\", identity, parent);\n\t\t},\n\t\tcapture: (child) => {\n\t\t\tconst own = child.session.events.slice(boundary);\n\t\t\tconst output = finalAssistantOutput(own);\n\t\t\tcaptured = {\n\t\t\t\tstopReason: epochStopReason(own),\n\t\t\t\t...output === void 0 ? {} : { output }\n\t\t\t};\n\t\t},\n\t\tterminal,\n\t\tsettle: (failure) => {\n\t\t\tconst { stopReason, output } = terminal(failure);\n\t\t\temit(\"subagent/end\", {\n\t\t\t\t...identity,\n\t\t\t\tstopReason,\n\t\t\t\t...output === void 0 ? {} : { lastAssistantMessage: output }\n\t\t\t}, parent);\n\t\t}\n\t};\n}\n/**\n* Why this child's epoch ended, for the terminal lifecycle edge and the\n* manager's own parent delivery. The child's own log is authoritative:\n* teardown succeeding says nothing about whether the model errored, hit its\n* token ceiling, or was cancelled, so deriving the reason from disposal would\n* report failed work as completed.\n*\n* {@link foldConsumedWork} supplies both halves the raw turn sequence cannot:\n* which turn accounts for the work this epoch consumed, and whether accepted\n* work was cancelled after it without any turn opening over it. A recorded\n* failure still wins over a cancellation — stopping a child that had already\n* failed does not turn its failure into a cancellation.\n* @param events - this epoch's own event suffix.\n* @returns its terminal stop reason; `completed` only for an epoch that both\n* closed cleanly and had nothing left to run.\n*/\nfunction epochStopReason(events) {\n\tconst { end, droppedUnrun } = foldConsumedWork(events);\n\tswitch (end?.data.reason.kind) {\n\t\tcase \"max-tokens\": return \"max-tokens\";\n\t\tcase \"aborted\":\n\t\tcase \"interrupted\": return \"aborted\";\n\t\tcase \"error\": return \"error\";\n\t\tcase \"blocked\": return \"refusal\";\n\t\tcase void 0:\n\t\tcase \"completed\": return droppedUnrun ? \"aborted\" : \"completed\";\n\t\t/* v8 ignore next 3 -- `TurnEndReason` is merge-extensible, so this arm needs a\n\t\t* backend that adds a variant; treating an unnameable reason as success would\n\t\t* report failed work as completed. */\n\t\tdefault: return \"error\";\n\t}\n}\n/** Render any listener-thrown value without letting coercion escape containment. */\nfunction renderThrown(value) {\n\ttry {\n\t\treturn value instanceof Error ? `${value.name}: ${value.message}` : String(value);\n\t} catch {\n\t\treturn \"<unrenderable thrown value>\";\n\t}\n}\n//#endregion\n//#region lib/types/descriptor.js\n/**\n* The durable subagent-child descriptor: the versioned, model-hidden\n* `subagent/descriptor` session event that identifies every session-backed\n* subagent and records whether it is one-shot or continuable. Continuable\n* descriptors additionally preserve the declared composition required for\n* cold resume. Providers append it turn-enclosed in the child's initial turn.\n*\n* The descriptor deliberately snapshots explicit fields rather than the\n* merge-extensible `AgentOptions` object: an unrelated extension value cannot\n* make continuation fail merely because it is not JSON, and later composition\n* inputs require a deliberate {@link SUBAGENT_DESCRIPTOR_VERSION} change. It\n* omits `subagentDepth` — cold resume trusts the persisted header's\n* `delegationDepth` as the monotone floor — and `outputSchema`, which belongs\n* to one activation's result contract rather than durable child composition.\n* Per-activation knobs such as `maxTokens` are omitted for the same reason as\n* `outputSchema`: they budget one activation. Cold resume requires the exact\n* live parent for authorization but reconstructs child options only from the\n* durable descriptor, so it neither restores the prior budget nor inherits\n* the parent's current one; the resumed route's defaults apply instead.\n*\n* @module @deepseek-ai/dsh-subagent/descriptor\n*/\n/**\n* The current descriptor format version, stamped into every appended\n* `subagent/descriptor` event and required verbatim by {@link foldSubagentDescriptor}.\n* Supporting another composition input is a deliberate version change, never\n* an implicit extra field.\n*/\nconst SUBAGENT_DESCRIPTOR_VERSION = 2;\nconst DESCRIPTOR_BASE_KEYS = [\n\t\"version\",\n\t\"mode\",\n\t\"provider\",\n\t\"label\"\n];\nconst ONE_SHOT_DESCRIPTOR_KEYS = new Set(DESCRIPTOR_BASE_KEYS);\nconst CONTINUABLE_DESCRIPTOR_KEYS = new Set([\n\t...DESCRIPTOR_BASE_KEYS,\n\t\"agentProvider\",\n\t\"agentModel\",\n\t\"persona\",\n\t\"toolFilter\"\n]);\nconst TOOL_FILTER_KEYS = new Set([\"allow\", \"deny\"]);\n/** Whether a persisted JSON value is an object record. */\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n/** Reject fields outside one versioned record's declared schema. */\nfunction assertKnownKeys(value, keys, path) {\n\tconst unknown = Object.keys(value).find((key) => !keys.has(key));\n\tif (unknown !== void 0) throw new Error(`persisted subagent descriptor ${path} has unknown field \"${unknown}\"`);\n}\n/** Read one optional string field from a persisted descriptor record. */\nfunction optionalString(value, key) {\n\tif (!Object.hasOwn(value, key)) return void 0;\n\tconst field = value[key];\n\tif (typeof field !== \"string\") throw new Error(`persisted subagent descriptor ${key} must be a string`);\n\treturn field;\n}\n/** Read one optional string-array field from a persisted tool restriction. */\nfunction optionalStringArray(value, key) {\n\tif (!Object.hasOwn(value, key)) return void 0;\n\tconst field = value[key];\n\tif (!Array.isArray(field)) throw new Error(`persisted subagent descriptor toolFilter.${key} must be an array of strings`);\n\tconst items = field;\n\tif (items.some((item) => typeof item !== \"string\")) throw new Error(`persisted subagent descriptor toolFilter.${key} must be an array of strings`);\n\treturn items;\n}\n/** Validate and reconstruct a persisted tool restriction. */\nfunction parseToolFilter(value) {\n\tif (!isRecord(value)) throw new Error(\"persisted subagent descriptor toolFilter must be an object\");\n\tassertKnownKeys(value, TOOL_FILTER_KEYS, \"toolFilter\");\n\tconst allow = optionalStringArray(value, \"allow\");\n\tconst deny = optionalStringArray(value, \"deny\");\n\tif (allow === void 0 && deny === void 0) throw new Error(\"persisted subagent descriptor toolFilter must declare allow and/or deny\");\n\treturn {\n\t\t...allow !== void 0 ? { allow } : {},\n\t\t...deny !== void 0 ? { deny } : {}\n\t};\n}\n/** Validate one persisted descriptor payload for the current runtime. */\nfunction parseSubagentDescriptor(value) {\n\tif (!isRecord(value)) throw new Error(\"persisted subagent descriptor payload must be an object\");\n\tconst version = value[\"version\"];\n\tif (typeof version !== \"number\") throw new Error(\"persisted subagent descriptor version must be a number\");\n\tif (version !== 2) return void 0;\n\tconst mode = value[\"mode\"];\n\tif (mode !== \"one-shot\" && mode !== \"continuable\") throw new Error(\"persisted subagent descriptor mode must be \\\"one-shot\\\" or \\\"continuable\\\"\");\n\tassertKnownKeys(value, mode === \"one-shot\" ? ONE_SHOT_DESCRIPTOR_KEYS : CONTINUABLE_DESCRIPTOR_KEYS, \"payload\");\n\tconst provider = value[\"provider\"];\n\tif (typeof provider !== \"string\") throw new Error(\"persisted subagent descriptor provider must be a string\");\n\tif (mode === \"one-shot\") {\n\t\tconst label = optionalString(value, \"label\");\n\t\treturn {\n\t\t\tversion: 2,\n\t\t\tmode,\n\t\t\tprovider,\n\t\t\t...label !== void 0 ? { label } : {}\n\t\t};\n\t}\n\tconst label = value[\"label\"];\n\tif (typeof label !== \"string\") throw new Error(\"persisted subagent descriptor label must be a string\");\n\tconst agentProvider = optionalString(value, \"agentProvider\");\n\tconst agentModel = optionalString(value, \"agentModel\");\n\tconst persona = optionalString(value, \"persona\");\n\tconst toolFilter = Object.hasOwn(value, \"toolFilter\") ? parseToolFilter(value[\"toolFilter\"]) : void 0;\n\treturn {\n\t\tversion: 2,\n\t\tmode,\n\t\tprovider,\n\t\tlabel,\n\t\t...agentProvider !== void 0 ? { agentProvider } : {},\n\t\t...agentModel !== void 0 ? { agentModel } : {},\n\t\t...persona !== void 0 ? { persona } : {},\n\t\t...toolFilter !== void 0 ? { toolFilter } : {}\n\t};\n}\nfunction snapshotSubagentDescriptor(input) {\n\tconst snapshot = snapshotJsonValue(input.mode === \"one-shot\" ? {\n\t\tversion: 2,\n\t\tmode: input.mode,\n\t\tprovider: input.provider,\n\t\t...input.label !== void 0 ? { label: input.label } : {}\n\t} : {\n\t\tversion: 2,\n\t\tmode: input.mode,\n\t\tprovider: input.provider,\n\t\tlabel: input.label,\n\t\t...input.agentProvider !== void 0 ? { agentProvider: input.agentProvider } : {},\n\t\t...input.agentModel !== void 0 ? { agentModel: input.agentModel } : {},\n\t\t...input.persona !== void 0 ? { persona: input.persona } : {},\n\t\t...input.toolFilter !== void 0 ? { toolFilter: input.toolFilter } : {}\n\t});\n\tif (snapshot === void 0) throw new Error(\"subagent descriptor is not losslessly JSON-serializable\");\n\treturn snapshot;\n}\n/**\n* Fold a persisted child log to its supported descriptor. The first\n* `subagent/descriptor` event is authoritative — the establishing provider\n* appends exactly one, so a later same-type event cannot rewrite the declared\n* composition.\n* @param events - the loaded child session events.\n* @returns the descriptor, or `undefined` when the log has none or its\n* version is not {@link SUBAGENT_DESCRIPTOR_VERSION} (the child cannot be\n* classified by this runtime).\n* @throws when a current-version persisted payload does not match its complete\n* declared schema.\n*/\nfunction foldSubagentDescriptor(events) {\n\tconst event = events.find((candidate) => candidate.type === \"subagent/descriptor\");\n\tif (event === void 0) return void 0;\n\treturn parseSubagentDescriptor(event.data);\n}\n//#endregion\n//#region lib/types/child-agent.js\n/**\n* Shared in-process child composition: the delegation-depth budget, the\n* durable session metadata, the resolved child `AgentOptions`, the delegated\n* policy seed, and the scoped setup a child agent needs. Both the one-shot\n* provider driver and the continuation manager compose children this way, so\n* depth accounting, lineage stamping, and delegation policy have one home.\n*\n* @module @deepseek-ai/dsh-subagent/child-agent\n*/\n/** Thrown when starting a child would exceed the requested depth cap. */\nvar SubagentDepthError = class extends Error {\n\tattemptedDepth;\n\tmaxDepth;\n\tconstructor(attemptedDepth, maxDepth) {\n\t\tsuper(`subagent depth ${attemptedDepth} exceeds maxDepth ${maxDepth}`);\n\t\tthis.attemptedDepth = attemptedDepth;\n\t\tthis.maxDepth = maxDepth;\n\t\tthis.name = \"SubagentDepthError\";\n\t}\n};\n/**\n* Resolve the child's delegation depth from its parent and enforce an optional\n* cap. The persisted parent header is the monotone floor, so a resumed parent\n* cannot delegate as if it were top-level.\n* @param parent - the delegating parent agent.\n* @param maxDepth - optional absolute cap the resolved depth must not exceed.\n* @returns the child's non-negative safe-integer depth.\n* @throws {SubagentDepthError} when the resolved depth exceeds `maxDepth`.\n* @throws {RangeError} when the resolved depth leaves the safe-integer range.\n*/\nfunction resolveChildDepth(parent, maxDepth) {\n\tconst childDepth = delegationDepthOf(parent) + 1;\n\tif (!Number.isSafeInteger(childDepth)) throw new RangeError(\"subagent child depth exceeds the safe-integer range\");\n\tif (maxDepth !== void 0 && childDepth > maxDepth) throw new SubagentDepthError(childDepth, maxDepth);\n\treturn childDepth;\n}\n/**\n* Resolve the child's `AgentOptions`: the parent's provider/model/maxTokens\n* route unless the request overrides it, stamped with the child's own\n* delegation depth.\n* @param parent - the delegating parent whose route the child inherits.\n* @param requested - per-child overrides, if any.\n* @param childDepth - the resolved delegation depth to stamp.\n* @returns the resolved options for `ctx.agents.create()`.\n*/\nfunction resolveChildAgentOptions(parent, requested, childDepth) {\n\tconst parentProvider = parent.options.provider;\n\tconst parentModel = parent.options.model;\n\tconst parentMaxTokens = parent.options.maxTokens;\n\treturn {\n\t\t...parentProvider !== void 0 ? { provider: parentProvider } : {},\n\t\t...parentModel !== void 0 ? { model: parentModel } : {},\n\t\t...parentMaxTokens !== void 0 ? { maxTokens: parentMaxTokens } : {},\n\t\t...requested,\n\t\tsubagentDepth: childDepth\n\t};\n}\n/**\n* Build the child session's durable creation metadata: the parent's workspace,\n* its direct lineage, coarse product origin, the recursion budget that must\n* survive persistence, the seed boundary that separates inherited parent\n* history from child work, and the composition the child runs under.\n*\n* The preset is read from the parent's LIVE scope chain rather than from its\n* header, because a parent that switched preset while blank runs on the newer\n* composition and its header still names the older one. Recording it is what\n* makes a child's history reconstructable: without it a cold read of the child\n* resolves the deployment default and rebuilds turns under a tool set the\n* child never had.\n* @param parent - the delegating parent agent.\n* @param childDepth - the resolved delegation depth to persist.\n* @param lineageSeedLength - how many leading events came from the parent's log.\n* @returns the `meta` for `ctx.agents.create()`.\n*/\nfunction childSessionMeta(parent, childDepth, lineageSeedLength) {\n\tconst parentHeader = parent.session.header;\n\tconst agentPreset = parent.ctx.get(\"agentPresets\")?.composedPreset(parent.ctx);\n\treturn {\n\t\t...parentHeader.cwd !== void 0 ? { cwd: parentHeader.cwd } : {},\n\t\t...agentPreset === void 0 ? {} : { agentPreset },\n\t\tparentSession: parentHeader.id,\n\t\torigin: \"subagent\",\n\t\tdelegationDepth: childDepth,\n\t\t...lineageSeedLength > 0 ? { seedLength: lineageSeedLength } : {}\n\t};\n}\n/**\n* Model-facing delegation-scope statement for every in-process child. A\n* runtime-context contribution rather than a system-prompt section, so the\n* deployment's system prompt stays uniform across parents and children.\n*/\nconst SUBAGENT_DELEGATION_CONTEXT = \"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\";\n/**\n* Compose one child inside its creation window: join its parent's preset,\n* register the fixed delegation-scope statement, then apply the child's own\n* shadowing persona section and tool restriction, all owned by the child's\n* scope and therefore invisible to its parent and siblings. Creation and cold\n* resume both pass through here.\n*\n* The join comes first and the child's own registrations second, which is the\n* order the layering already implies — the nearest scope wins a name, and a\n* per-child restriction intersects with everything its chain admits — but\n* stating it here keeps the two steps from being read as independent.\n*\n* The join and the per-child registrations live in ONE call because a child\n* composed without the join is exactly the defect this function exists to\n* prevent: with every model-facing row on the agent plane, a child that joins\n* no preset sees an empty tool registry and none of its parent's prompt\n* sections. Taking the parent as a parameter is what makes that omission\n* unrepresentable at the call sites.\n* @param childCtx - the child agent's scoped creation context.\n* @param parent - the delegating parent whose composition the child joins.\n* @param composition - the per-child persona and tool filter to install.\n*/\nfunction applyChildComposition(childCtx, parent, composition) {\n\tchildCtx.get(\"agentPresets\")?.composeFrom(childCtx, parent.ctx);\n\tchildCtx.systemPrompt.context({\n\t\tname: \"subagent:delegation\",\n\t\torder: 120,\n\t\ttext: SUBAGENT_DELEGATION_CONTEXT\n\t});\n\tif (composition.persona !== void 0) childCtx.systemPrompt.section({\n\t\tname: \"deployment:persona\",\n\t\torder: 0,\n\t\ttext: composition.persona\n\t});\n\tif (composition.toolFilter !== void 0) childCtx.tools.restrict(composition.toolFilter);\n}\n/**\n* Capture the policy to seed into one delegation. Call synchronously before\n* the child start's first await: a later parent switch belongs to the\n* parent's future, not to this child. Only the parent session's explicit\n* sandbox override is captured — never deployment defaults or one-shot\n* grants — and the approval policy is pinned to `'never'` regardless of the\n* parent's own policy.\n* @param parent - the delegating parent agent.\n* @returns the sandbox override (or `undefined` without one) and the approval pin.\n*/\nfunction captureDelegatedPolicyOverrides(parent) {\n\treturn {\n\t\tsandboxMode: parent.ctx.get(\"sandboxPolicy\")?.overrideOf(parent.session),\n\t\tapprovalPolicy: parent.ctx.get(\"approval\") === void 0 ? void 0 : \"never\"\n\t};\n}\n/**\n* Append the captured delegation policy onto the child's own log as\n* `source: 'delegation'` events inside the unpublished creation window, so the\n* child's effective policy is reconstructable from its log alone. Appends land\n* after any fork seed, so fresh policy wins stale seed state; later child\n* switches still win over these events.\n* @param childSession - the unpublished child's session.\n* @param overrides - the policy captured at delegation.\n*/\nfunction appendDelegatedPolicyOverrides(childSession, overrides) {\n\tif (overrides.sandboxMode !== void 0) childSession.append(\"sandbox/mode\", {\n\t\tmode: overrides.sandboxMode,\n\t\tsource: \"delegation\"\n\t});\n\tif (overrides.approvalPolicy !== void 0) childSession.append(\"approval/policy\", {\n\t\tpolicy: overrides.approvalPolicy,\n\t\tsource: \"delegation\"\n\t});\n}\n//#endregion\n//#region lib/types/descriptor-seed.js\n/**\n* Seeding of a continuable child's durable descriptor event: the model-hidden\n* record of the child's declared composition before its first request, so a\n* later cold resume can reconstruct it from its own log.\n*\n* @module @deepseek-ai/dsh-subagent/descriptor-seed\n*/\n/**\n* Build the child's creation seed: any inherited parent-history prefix followed\n* by one model-hidden, between-turn `descriptor` event. Staging through a\n* `Session` assigns the sequence number and enforces the same lossless-JSON\n* rules the durable log does.\n* @param childId - the reserved child session id the staged log belongs to.\n* @param seed - the inherited completed-turn prefix, or `undefined` for a fresh child.\n* @param descriptor - the snapshotted composition record to persist.\n* @returns the complete seed events, contiguous from sequence zero.\n*/\nfunction seedDescriptorTurn(childId, seed, descriptor) {\n\tconst staged = Session.create(childId, seed);\n\tstaged.append(\"subagent/descriptor\", descriptor);\n\treturn [...staged.events];\n}\n//#endregion\n//#region lib/types/continuation.js\n/**\n* Internal continuable-subagent manager: stable child ids, descriptor\n* persistence, activation admission, the live ownership graph, cold resume,\n* child-first disposal, and settlement delivery to the parent, behind\n* `ctx.subagents`.\n*\n* A continuable child has one durable Session and at most one process-local\n* {@link Activation} — one residency epoch for a reconstructed child Agent. An\n* Activation is not a request, result, cancellation, or Task boundary: it may\n* execute many FIFO turns and stays resident while descendants it created are\n* still running. The Agent inbox is the only turn queue, so this manager owns\n* residency while the Agent loop owns all turn ordering and execution. No\n* continuable path creates a Task or an intermediate result-bearing wrapper.\n*\n* Because residency is this manager's alone to end, telling the parent that a\n* child settled is its job too. An external `subagent/end` listener cannot do\n* it correctly: that payload names no parent, the child handle is already\n* disposed by then, and the release that wakes the parent's own settlement\n* watcher has already run. See {@link SubagentContinuationManager.notifySettlement}.\n*\n* @module @deepseek-ai/dsh-subagent\n*/\n/**\n* Read one Activation's current disposal transaction. This indirection exists\n* because TypeScript would otherwise narrow repeated reads of the mutable field\n* inside a long-lived closure to constants instead of re-reading runtime state.\n* @param activation - the Activation to inspect.\n* @returns the in-flight or settled disposal, or `undefined` while resident.\n*/\nfunction disposalOf(activation) {\n\treturn activation.disposal;\n}\n/**\n* One line telling a parent that a background child is finished and why, in\n* the parent's own task vocabulary.\n* @param childId - the durable child the parent knows by id.\n* @param stopReason - how the child's last ordinary turn ended.\n* @returns the model-facing opening line of the settlement notice.\n*/\nfunction settlementSummary(childId, stopReason) {\n\tconst subject = `Background subagent ${childId}`;\n\tswitch (stopReason) {\n\t\tcase \"completed\": return `${subject} finished and will do no further work unless you send it more.`;\n\t\tcase \"aborted\": return `${subject} was stopped before it finished.`;\n\t\tcase \"max-tokens\": return `${subject} ran out of room before it finished.`;\n\t\tcase \"refusal\": return `${subject} declined the task.`;\n\t\tcase \"error\": return `${subject} failed before it finished.`;\n\t\t/* v8 ignore next 4 -- `SubagentResult['stopReason']` is merge-extensible, so this arm\n\t\t* needs a backend that adds a variant; an unnameable ending is reported as unfinished\n\t\t* rather than silently as success. */\n\t\tdefault: return `${subject} ended abnormally (${String(stopReason)}) before it finished.`;\n\t}\n}\n/** Serialize each durable child's delivery, release, and disposal. */\nvar ChildLock = class {\n\ttails = /* @__PURE__ */ new Map();\n\t/**\n\t* Run `operation` after every previously queued operation for `childId`.\n\t* @param childId - the durable child whose operations are linearized.\n\t* @param operation - the critical section to run in order.\n\t* @returns the operation's own settlement.\n\t*/\n\trun(childId, operation) {\n\t\tconst result = (this.tails.get(childId) ?? Promise.resolve()).then(operation, operation);\n\t\tconst tail = result.then(() => void 0, () => void 0);\n\t\tthis.tails.set(childId, tail);\n\t\ttail.then(() => {\n\t\t\tif (this.tails.get(childId) === tail) this.tails.delete(childId);\n\t\t});\n\t\treturn result;\n\t}\n};\n/**\n* The continuable-subagent orchestration service behind `ctx.subagents`. Tool\n* schema and host adapters are consumers of this one contract; foreground\n* one-shot delegation keeps calling `ctx.subagents.start()` and never enters\n* this lifecycle.\n*/\nvar SubagentContinuationManager = class {\n\tctx;\n\thost;\n\tsetupRegistry;\n\t/** Child session id → its live Activation. Process-local, never durable. */\n\tactivations = /* @__PURE__ */ new Map();\n\t/** Materializations admitted before drain, tracked through publication or rollback. */\n\tmaterializations = /* @__PURE__ */ new Set();\n\tlocks = new ChildLock();\n\t/** Structural Cordis owner of every Activation handle. */\n\townerCtx;\n\t/**\n\t* Exact roots whose host teardown has begun, with the live lineage members\n\t* observed under each root. Entries remain until that exact root leaves the\n\t* Agent registry, closing admission throughout its host's teardown without\n\t* poisoning a later same-id replacement.\n\t*/\n\tclosingScopes = /* @__PURE__ */ new Map();\n\tdraining = false;\n\tconstructor(ctx, host, setupRegistry) {\n\t\tthis.ctx = ctx;\n\t\tthis.host = host;\n\t\tthis.setupRegistry = setupRegistry;\n\t\tconst scope = ctx.plugin(function activationOwner() {});\n\t\tthis.ownerCtx = scope.ctx;\n\t\tctx.on(\"agent/disposed\", ({ agent }) => {\n\t\t\tthis.closingScopes.delete(agent);\n\t\t});\n\t\tctx.effect(function* () {\n\t\t\tyield scope.dispose;\n\t\t\tyield () => this.drain();\n\t\t}.bind(this), \"subagents.continuations()\");\n\t}\n\t/**\n\t* Start one continuable background child: reserve its durable identity,\n\t* resolve the provider's detached creation spec, create the child Agent\n\t* through the private activation-owner scope, establish any continuable-parent\n\t* ownership, and submit the initial prompt. Resolves when inbox acceptance\n\t* yields the message id — without waiting for the turn to start or for the\n\t* message to reach the Session log.\n\t*\n\t* Every failure before that acceptance rejects without either id, disposing\n\t* any created handle and rolling back the Activation and parent ownership.\n\t* The caller signal owns lookup, materialization, and admission only until\n\t* acceptance; afterwards the manager owns the Activation independently.\n\t* @param spec - provider, delegation request, and caller cancellation.\n\t* @returns the durable child id and the accepted initial prompt's message id.\n\t*/\n\tasync startContinuable(spec) {\n\t\tconst request = spec.request;\n\t\tconst parent = request.parent;\n\t\tthis.assertAdmitting(parent);\n\t\tthis.requirePersistence();\n\t\tassertSubagentMaxDepth(request.maxDepth);\n\t\tconst childId = SessionId(randomUUID());\n\t\tconst childDepth = resolveChildDepth(parent, request.maxDepth);\n\t\tconst agentProvider = request.agentOptions?.provider ?? parent.options.provider;\n\t\tconst agentModel = request.agentOptions?.model ?? parent.options.model;\n\t\tconst descriptor = snapshotSubagentDescriptor({\n\t\t\tmode: \"continuable\",\n\t\t\tprovider: spec.provider,\n\t\t\tlabel: spec.label,\n\t\t\t...agentProvider !== void 0 ? { agentProvider } : {},\n\t\t\t...agentModel !== void 0 ? { agentModel } : {},\n\t\t\t...request.persona !== void 0 ? { persona: request.persona } : {},\n\t\t\t...request.toolFilter !== void 0 ? { toolFilter: request.toolFilter } : {}\n\t\t});\n\t\tconst delegatedPolicies = captureDelegatedPolicyOverrides(parent);\n\t\tconst prepared = await this.host.prepareContinuable(spec.provider, {\n\t\t\tsessionId: childId,\n\t\t\tparent,\n\t\t\tsignal: spec.signal\n\t\t});\n\t\tspec.signal.throwIfAborted();\n\t\tthis.assertAdmitting(parent);\n\t\tconst lineageSeedLength = prepared.seed?.length ?? 0;\n\t\tconst seed = seedDescriptorTurn(childId, prepared.seed, descriptor);\n\t\treturn {\n\t\t\tchildId,\n\t\t\tmessageId: await this.locks.run(childId, async () => {\n\t\t\t\tconst activation = await this.materialize({\n\t\t\t\t\tchildId,\n\t\t\t\t\tprovider: spec.provider,\n\t\t\t\t\tparent,\n\t\t\t\t\tcreate: {\n\t\t\t\t\t\tseed,\n\t\t\t\t\t\tmeta: childSessionMeta(parent, childDepth, lineageSeedLength),\n\t\t\t\t\t\tdelegatedPolicies\n\t\t\t\t\t},\n\t\t\t\t\tagentOptions: resolveChildAgentOptions(parent, request.agentOptions, childDepth),\n\t\t\t\t\tcomposition: {\n\t\t\t\t\t\tpersona: request.persona,\n\t\t\t\t\t\ttoolFilter: request.toolFilter\n\t\t\t\t\t},\n\t\t\t\t\tsignal: spec.signal\n\t\t\t\t});\n\t\t\t\treturn this.submitMaterialized(activation, request.prompt, { kind: \"user\" }, parent, spec.signal);\n\t\t\t})\n\t\t};\n\t}\n\t/**\n\t* Deliver one later message to a known continuable child as its next FIFO\n\t* turn. Routing depends only on Activation residency: a `running` Activation\n\t* enqueues, a `waiting` one wakes the same Agent, and an absent one\n\t* cold-resumes a new Activation from the persisted Session. The Agent inbox\n\t* is the only queue, so every accepted message has one observable order.\n\t*\n\t* The caller signal owns lookup, materialization, and admission only until\n\t* inbox acceptance; afterwards the accepted turn cannot be cancelled through\n\t* this service.\n\t* @param parent - the exact live direct parent authorizing this delivery.\n\t* @param childId - the durable child session id.\n\t* @param content - the user-role content to deliver.\n\t* @param options - the message source fields and caller cancellation.\n\t* @returns the accepted message's inbox id.\n\t* @throws when parent authority, availability, or admission rejects the delivery.\n\t*/\n\tasync followup(parent, childId, content, options) {\n\t\tthis.assertAdmitting(parent);\n\t\twhile (true) {\n\t\t\tconst live = await this.locks.run(childId, async () => {\n\t\t\t\tconst activation = this.activations.get(childId);\n\t\t\t\tif (activation === void 0) return this.coldResume(parent, childId, content, options);\n\t\t\t\t/* v8 ignore next 3 -- the send-versus-dispose cutoff: reaching this arm needs a\n\t\t\t\t* delivery to observe the transaction inside the same critical section that opened it,\n\t\t\t\t* which no test can schedule deterministically. The behavior is covered end-to-end by\n\t\t\t\t* \"cold-resumes a delivery that lost the race with final disposal\". */\n\t\t\t\tif (activation.disposal !== void 0) return activation.disposal.then(() => void 0, () => void 0);\n\t\t\t\treturn this.submitAdmitted(activation, content, options.source, parent, options.signal);\n\t\t\t});\n\t\t\t/* v8 ignore start -- only the lost-cutoff arm above returns undefined, so only that\n\t\t\t* race reaches the retry below, which then cold-resumes a new Activation. */\n\t\t\tif (live !== void 0) return live;\n\t\t\tthis.assertAdmitting(parent);\n\t\t\toptions.signal.throwIfAborted();\n\t\t}\n\t}\n\t/**\n\t* Interrupt one live continuable child's current turn. Admission is\n\t* synchronous and the effect is asynchronous: this authorizes the caller,\n\t* requests `Agent.cancel(cause, { keepInbox: true })` on the target, and\n\t* returns without waiting for the target to observe the signal or reach\n\t* quiescence. The Activation, its handle, accepted unclaimed inbox work, and\n\t* already-published descendants are untouched; work already claimed into the\n\t* interrupted turn is not requeued. Once the interrupted driver is idle, a\n\t* waking send resumes the parked queue.\n\t*\n\t* An absent target is an accepted no-op, which uniformly covers natural\n\t* completion races, repeated requests, one-shot ids, and unknown ids without\n\t* consulting the durable catalog. A target whose disposal transaction is\n\t* already open is likewise an accepted no-op after authorization.\n\t* @param targetSessionId - the durable child session id to interrupt.\n\t* @param authority - the human parent address or exact live ancestor Agent.\n\t* @throws {SubagentError} `UNAUTHORIZED` when the presented authority does\n\t* not own the live target: a stale or self-targeting ancestor caller, a\n\t* parent address that is not the live target's durable direct parent, or\n\t* an ancestor outside the target's recorded live lineage.\n\t*/\n\tinterrupt(targetSessionId, authority) {\n\t\tif (authority.kind === \"ancestor\") {\n\t\t\tconst caller = authority.agent;\n\t\t\tif (this.ctx.agents.get(caller.id) !== caller) throw new SubagentError(`interrupting \"${targetSessionId}\" requires the exact live ancestor agent`, \"UNAUTHORIZED\");\n\t\t\tif (caller.id === targetSessionId) throw new SubagentError(`agent \"${caller.id}\" cannot interrupt itself`, \"UNAUTHORIZED\");\n\t\t}\n\t\tconst activation = this.activations.get(targetSessionId);\n\t\tif (activation === void 0) return;\n\t\tif (authority.kind === \"user\") {\n\t\t\tif (activation.handle.agent.session.header.parentSession !== authority.parentSessionId) throw new SubagentError(`subagent \"${targetSessionId}\" belongs to another parent session`, \"UNAUTHORIZED\");\n\t\t} else if (!activation.ancestry.has(authority.agent)) throw new SubagentError(`subagent \"${targetSessionId}\" is not a live descendant of agent \"${authority.agent.id}\"`, \"UNAUTHORIZED\");\n\t\tif (activation.disposal !== void 0) return;\n\t\tactivation.handle.agent.cancel(authority.kind === \"user\" ? { kind: \"user\" } : { kind: \"parent\" }, { keepInbox: true });\n\t}\n\t/**\n\t* Deliver explicitly selected content from one resident continuable child to\n\t* its durable direct parent. Sender authorization, parent resolution, and\n\t* send acceptance share one no-await span. Reporting neither concludes the\n\t* child's turn nor changes its Activation lifetime.\n\t* @param child - exact live reporting child; this is the authority credential.\n\t* @param content - selected model-facing content.\n\t* @param options - scheduling policy and pre-acceptance cancellation.\n\t* @returns the stable identity of the message accepted by the parent.\n\t* @throws {SubagentError} when the sender is unauthorized, the parent is not\n\t* live, or continuation admission is closing.\n\t*/\n\tasync reportFrom(child, content, options) {\n\t\toptions.signal.throwIfAborted();\n\t\tthis.assertAdmitting(child);\n\t\tconst activation = this.authorizeReporter(child);\n\t\tconst parent = this.resolveReportParent(child);\n\t\treturn this.deliverReport(activation, parent, content, options.delivery);\n\t}\n\t/** Authorize only the exact Agent of one resident Activation. */\n\tauthorizeReporter(child) {\n\t\tconst activation = this.activations.get(child.id);\n\t\tif (activation === void 0 || activation.handle.agent !== child) throw new SubagentError(`agent \"${child.id}\" is not a live continuable subagent and cannot report`, \"UNAUTHORIZED\");\n\t\t/* v8 ignore next 6 -- only a synchronous re-entrant disposer can open this\n\t\t* transaction between exact-agent authorization and this no-await cutoff. */\n\t\tif (activation.disposal !== void 0) throw new SubagentError(`subagent \"${child.id}\" activation is being disposed; the report was not delivered`, \"ACTIVATION_CLOSING\");\n\t\treturn activation;\n\t}\n\t/** Resolve the reporting child's live direct parent from durable lineage. */\n\tresolveReportParent(child) {\n\t\tconst parentId = child.session.header.parentSession;\n\t\t/* v8 ignore next -- every continuation-managed child has direct-parent metadata. */\n\t\tconst parent = parentId === void 0 ? void 0 : this.ctx.agents.get(parentId);\n\t\tif (parent === void 0) throw new SubagentError(\"direct parent is not live; report was not delivered\", \"PARENT_UNAVAILABLE\");\n\t\treturn parent;\n\t}\n\t/** Deliver one framed report through the selected parent scheduling preset. */\n\tdeliverReport(activation, parent, content, delivery) {\n\t\tconst message = createUserMessage({\n\t\t\tcontent: [{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `Background subagent ${activation.childId} reported:`\n\t\t\t}, ...content],\n\t\t\tsource: {\n\t\t\t\tkind: \"subagent-report\",\n\t\t\t\tform: \"relay\",\n\t\t\t\tsenderSessionId: activation.childId\n\t\t\t}\n\t\t});\n\t\tif (delivery === \"wakeup\") this.sendWaking(parent, message, () => {\n\t\t\tthis.sendReport(parent, message, delivery);\n\t\t});\n\t\telse this.sendReport(parent, message, delivery);\n\t\treturn message.id;\n\t}\n\t/**\n\t* Perform one waking send to a parent, accounted against that parent's own\n\t* Activation when it has one. Registering the id before the send is what\n\t* keeps a continuation-managed parent from being judged quiescent in the\n\t* window between `followup()` and the microtask that admits it.\n\t* @param parent - the exact live parent receiving the waking message.\n\t* @param message - the message whose id is accounted.\n\t* @param send - the synchronous waking send to perform.\n\t*/\n\tsendWaking(parent, message, send) {\n\t\tconst parentActivation = this.activations.get(parent.id);\n\t\tif (parentActivation !== void 0 && parentActivation.handle.agent === parent) this.admitWaking(parentActivation, message.id, send);\n\t\telse send();\n\t}\n\t/** Send one report while translating only the parent's own rejection. */\n\tsendReport(parent, message, delivery) {\n\t\ttry {\n\t\t\tif (delivery === \"wakeup\") parent.followup(message);\n\t\t\telse parent.inject(message);\n\t\t} catch (error) {\n\t\t\tthrow new SubagentError(\"direct parent is not live; report was not delivered\", \"PARENT_UNAVAILABLE\", { cause: error });\n\t\t}\n\t}\n\t/**\n\t* Close admission, await every already-admitted materialization through\n\t* publication or rollback, then dispose the stable live Activation forest\n\t* child-first. Sibling branches drain independently: one failure is recorded\n\t* but never prevents the remaining handles from being attempted, and the\n\t* aggregate rejects only after every branch settles.\n\t* @returns once materialization is quiescent and every live Activation released its handle.\n\t* @throws an aggregate error when any branch failed to release.\n\t*/\n\tasync drain() {\n\t\tthis.draining = true;\n\t\tawait Promise.all([...this.materializations].map((materialization) => materialization.settled));\n\t\tconst owned = /* @__PURE__ */ new Set();\n\t\tfor (const activation of this.activations.values()) for (const child of activation.ownedChildren) owned.add(child);\n\t\tconst roots = [...this.activations.values()].filter((activation) => !owned.has(activation.childId));\n\t\tawait this.disposeRoots(roots, \"activation(s)\");\n\t}\n\t/**\n\t* Stop only the continuable descendants of exact live host-owned parents.\n\t* Admission stays closed for those parent trees until each exact parent\n\t* leaves the Agent registry; unrelated trees and manager-wide admission stay\n\t* live.\n\t* @param parents - exact live roots whose continuable descendants must stop.\n\t* @returns once every retained descendant Activation released its handle.\n\t* @throws an aggregate error after all scoped branches settle when any failed.\n\t*/\n\tasync drainDescendants(parents) {\n\t\tconst roots = new Set(parents.filter((parent) => this.ctx.agents.get(parent.id) === parent));\n\t\tif (roots.size === 0) return;\n\t\tfor (const root of roots) this.closingMembers(root).add(root);\n\t\tconst targets = [];\n\t\tfor (const activation of this.activations.values()) {\n\t\t\tconst lineage = this.liveLineage(activation.handle.agent);\n\t\t\tconst owners = [...roots].filter((root) => activation.handle.agent !== root && activation.ancestry.has(root));\n\t\t\tif (owners.length === 0) continue;\n\t\t\ttargets.push(activation);\n\t\t\tfor (const owner of owners) {\n\t\t\t\tconst members = this.closingMembers(owner);\n\t\t\t\tmembers.add(activation.handle.agent);\n\t\t\t\tfor (const agent of lineage) members.add(agent);\n\t\t\t}\n\t\t}\n\t\tconst materializations = [...this.materializations].filter((materialization) => {\n\t\t\tconst owners = [...roots].filter((root) => materialization.lineage.includes(root));\n\t\t\tfor (const owner of owners) {\n\t\t\t\tconst members = this.closingMembers(owner);\n\t\t\t\tfor (const agent of materialization.lineage) members.add(agent);\n\t\t\t}\n\t\t\treturn owners.length > 0;\n\t\t});\n\t\tconst ownedTargets = /* @__PURE__ */ new Set();\n\t\tfor (const activation of targets) for (const child of activation.ownedChildren) ownedTargets.add(child);\n\t\tconst targetRoots = targets.filter((activation) => !ownedTargets.has(activation.childId));\n\t\tfor (const activation of targets) this.dispose(activation).catch(() => void 0);\n\t\tawait Promise.all(materializations.map((materialization) => materialization.settled));\n\t\tawait this.disposeRoots(targetRoots, \"scoped activation(s)\");\n\t}\n\t/** Dispose independent roots and report every branch failure after all settle. */\n\tasync disposeRoots(roots, failureSubject) {\n\t\tconst reasons = (await Promise.all(roots.map(async (activation) => {\n\t\t\ttry {\n\t\t\t\tawait this.dispose(activation);\n\t\t\t\treturn;\n\t\t\t} catch (error) {\n\t\t\t\treturn error;\n\t\t\t}\n\t\t}))).filter((failure) => failure !== void 0);\n\t\tif (reasons.length > 0) throw new SubagentError(`continuable subagent teardown failed for ${reasons.length} ${failureSubject}: ` + reasons.map((reason) => errorChain(reason)).join(\"; \"), \"ACTIVATION_TEARDOWN_FAILED\");\n\t}\n\t/** Return the retained member set for one exact scoped-teardown root. */\n\tclosingMembers(root) {\n\t\tconst existing = this.closingScopes.get(root);\n\t\tif (existing !== void 0) return existing;\n\t\tconst members = /* @__PURE__ */ new Set();\n\t\tthis.closingScopes.set(root, members);\n\t\treturn members;\n\t}\n\t/**\n\t* Return the exact currently resolvable ancestry from `agent` upward. The\n\t* first element is always the supplied identity, even when it is already\n\t* stale; each ancestor after it must be the registry's current exact entry.\n\t*/\n\tliveLineage(agent) {\n\t\tconst lineage = [agent];\n\t\tconst seen = new Set([agent.id]);\n\t\tlet parentSession = agent.session.header.parentSession;\n\t\twhile (parentSession !== void 0) {\n\t\t\tconst parent = this.ctx.agents.get(parentSession);\n\t\t\tif (parent === void 0 || seen.has(parent.id)) break;\n\t\t\tlineage.push(parent);\n\t\t\tseen.add(parent.id);\n\t\t\tparentSession = parent.session.header.parentSession;\n\t\t}\n\t\treturn lineage;\n\t}\n\t/**\n\t* The teardown that closed continuable admission for this agent's lineage.\n\t* `'manager'` is the whole manager draining; an Agent is the exact scoped root\n\t* whose forest is closing.\n\t* @param agent - the agent whose lineage is tested.\n\t* @returns the closing teardown, or `undefined` while admission is open.\n\t*/\n\tclosingTeardownFor(agent) {\n\t\tif (this.draining) return \"manager\";\n\t\tconst lineage = this.liveLineage(agent);\n\t\tfor (const [root, members] of this.closingScopes) if (members.has(agent) || lineage.includes(root)) return root;\n\t}\n\t/** Reject new admission once the manager or this exact parent tree began draining. */\n\tassertAdmitting(agent) {\n\t\tconst closing = this.closingTeardownFor(agent);\n\t\tif (closing === void 0) return;\n\t\tthrow new SubagentError(closing === \"manager\" ? \"continuable subagents are draining; the operation was not admitted\" : `continuable subagents below parent \"${closing.id}\" are draining; the operation was not admitted`, \"DRAINING\");\n\t}\n\t/**\n\t* Derive residency from Agent quiescence and the owned-child set. `running`\n\t* covers an active admission, an open turn, or accepted waking inbox work.\n\t*\n\t* `Agent.status` alone is insufficient: it stays `idle` between an accepted\n\t* waking send and the microtask that admits it, so a synchronous inbox\n\t* observer would see `settled` while a turn is already queued. `accepted`\n\t* holds the ids this manager admitted but has not yet seen drained.\n\t*/\n\tstateOf(activation) {\n\t\tif (activation.handle.agent.status === \"running\" || activation.accepted.size > 0) return \"running\";\n\t\tif (activation.ownedChildren.size > 0) return \"waiting\";\n\t\treturn \"settled\";\n\t}\n\t/**\n\t* Cold-resume a persisted child: inspect and authorize its Session, fold the\n\t* generic descriptor, create the Activation through `ctx.agents.resume()`,\n\t* and submit the waiting turn. This never dispatches through a subagent\n\t* provider — the persisted Session already holds the initial prefix and the\n\t* descriptor is the whole reconstruction input.\n\t*/\n\tasync coldResume(parent, childId, content, options) {\n\t\tconst persistence = this.requirePersistence();\n\t\tlet loaded;\n\t\ttry {\n\t\t\tloaded = await persistence.inspect(childId, options.signal);\n\t\t} catch (error) {\n\t\t\toptions.signal.throwIfAborted();\n\t\t\tthrow new SubagentError(`subagent \"${childId}\" is unavailable`, \"NOT_RESUMABLE\", { cause: error });\n\t\t}\n\t\toptions.signal.throwIfAborted();\n\t\tthis.assertAdmitting(parent);\n\t\tthis.authorizeLineage(parent, childId, loaded.meta.parentSession);\n\t\tconst descriptor = foldSubagentDescriptor(loaded.events.slice(loaded.meta.seedLength ?? 0));\n\t\tif (descriptor === void 0 || descriptor.mode !== \"continuable\") throw new SubagentError(`subagent \"${childId}\" has no supported continuation state and cannot be resumed; do not retry send_message with this id`, \"NOT_RESUMABLE\");\n\t\tlet activation;\n\t\ttry {\n\t\t\tactivation = await this.materialize({\n\t\t\t\tchildId,\n\t\t\t\tprovider: descriptor.provider,\n\t\t\t\tparent,\n\t\t\t\tagentOptions: {\n\t\t\t\t\t...descriptor.agentProvider !== void 0 ? { provider: descriptor.agentProvider } : {},\n\t\t\t\t\t...descriptor.agentModel !== void 0 ? { model: descriptor.agentModel } : {}\n\t\t\t\t},\n\t\t\t\tcomposition: {\n\t\t\t\t\tpersona: descriptor.persona,\n\t\t\t\t\ttoolFilter: descriptor.toolFilter\n\t\t\t\t},\n\t\t\t\tsignal: options.signal\n\t\t\t});\n\t\t} catch (error) {\n\t\t\toptions.signal.throwIfAborted();\n\t\t\tif (error instanceof SubagentError) throw error;\n\t\t\tthrow new SubagentError(`subagent \"${childId}\" is unavailable`, \"NOT_RESUMABLE\", { cause: error });\n\t\t}\n\t\treturn this.submitMaterialized(activation, content, options.source, parent, options.signal);\n\t}\n\t/**\n\t* Submit to a freshly materialized Activation or roll it back completely.\n\t* @param activation - the just-published Activation to admit or release.\n\t* @param content - the initial or resumed message content.\n\t* @param source - durable fields naming who supplied the accepted message.\n\t* @param parent - the live direct parent authorizing admission.\n\t* @param signal - caller cancellation owning admission until acceptance.\n\t* @returns the accepted inbox message id.\n\t*/\n\tasync submitMaterialized(activation, content, source, parent, signal) {\n\t\ttry {\n\t\t\treturn this.submitAdmitted(activation, content, source, parent, signal);\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- rollback disposal failures must not mask the\n\t\t\t* pre-acceptance signal, drain, or lifecycle failure. */\n\t\t\tawait this.dispose(activation).catch(() => void 0);\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/**\n\t* Create or resume the child Agent through the private activation-owner\n\t* scope, install the handle in a fresh Activation, and register ownership on\n\t* a continuation-managed parent. Rejection leaves no Activation, no handle,\n\t* and no ownership membership.\n\t*/\n\tmaterialize(inputs) {\n\t\tthis.assertAdmitting(inputs.parent);\n\t\tconst settled = Promise.withResolvers();\n\t\tconst lineage = this.liveLineage(inputs.parent);\n\t\tconst materialization = {\n\t\t\tlineage,\n\t\t\tsettled: settled.promise\n\t\t};\n\t\tthis.materializations.add(materialization);\n\t\treturn this.materializeTracked(inputs, lineage).finally(() => {\n\t\t\tthis.materializations.delete(materialization);\n\t\t\tsettled.resolve();\n\t\t});\n\t}\n\t/**\n\t* Perform one tracked materialization. The caller keeps the drain barrier\n\t* registered until this either returns a resident Activation or finishes\n\t* rollback.\n\t*/\n\tasync materializeTracked(inputs, parentLineage) {\n\t\tconst { childId, provider, parent, create } = inputs;\n\t\tinputs.signal.throwIfAborted();\n\t\tconst setup = (childCtx) => {\n\t\t\tif (create !== void 0) appendDelegatedPolicyOverrides(childCtx.agent.session, create.delegatedPolicies);\n\t\t\tapplyChildComposition(childCtx, parent, inputs.composition);\n\t\t\treturn this.setupRegistry.apply(childCtx);\n\t\t};\n\t\tconst observer = this.host.observeActivation(provider, childId, parent);\n\t\tconst handle = create === void 0 ? await this.ownerCtx.agents.resume({\n\t\t\tresumeSessionId: childId,\n\t\t\tagentOptions: inputs.agentOptions,\n\t\t\tsignal: inputs.signal,\n\t\t\tsetup\n\t\t}) : await this.ownerCtx.agents.create({\n\t\t\tsessionId: childId,\n\t\t\tmeta: create.meta,\n\t\t\tseed: create.seed,\n\t\t\tagentOptions: inputs.agentOptions,\n\t\t\tsignal: inputs.signal,\n\t\t\tsetup\n\t\t});\n\t\tconst activation = {\n\t\t\tchildId,\n\t\t\tparentSession: parent.id,\n\t\t\tprovider,\n\t\t\thandle,\n\t\t\tancestry: new WeakSet([handle.agent, ...parentLineage]),\n\t\t\townedChildren: /* @__PURE__ */ new Set(),\n\t\t\tobserver,\n\t\t\tdisposal: void 0,\n\t\t\taccepted: /* @__PURE__ */ new Set(),\n\t\t\tannounced: false,\n\t\t\tpoke: Promise.withResolvers()\n\t\t};\n\t\tthis.activations.set(childId, activation);\n\t\ttry {\n\t\t\tinputs.signal.throwIfAborted();\n\t\t\tthis.assertAdmitting(parent);\n\t\t\tthis.acquireOwnership(parent, childId);\n\t\t\thandle.agent.ctx.on(\"agent/inbox/claimed\", ({ message }) => {\n\t\t\t\t/* v8 ignore next -- a claim of an id this manager never admitted needs\n\t\t\t\t* another sender on the same child, which no current path allows. */\n\t\t\t\tif (activation.accepted.delete(message.id)) this.wake(activation);\n\t\t\t});\n\t\t\thandle.agent.ctx.on(\"agent/inbox/discarded\", ({ message }) => {\n\t\t\t\tif (activation.accepted.delete(message.id)) this.wake(activation);\n\t\t\t});\n\t\t\tobserver.start(handle.agent);\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- rollback failure must not mask the admission failure\n\t\t\t* that prevented this operation from returning an accepted message id. */\n\t\t\tawait this.rollbackUnpublished(activation).catch(() => void 0);\n\t\t\tthrow error;\n\t\t}\n\t\tthis.watchSettlement(activation);\n\t\treturn activation;\n\t}\n\t/**\n\t* Release an Activation whose start edge was not published. The memoized\n\t* transaction remains in the live map until handle disposal settles, so a\n\t* concurrent drain or delivery observes the same closing boundary.\n\t*/\n\trollbackUnpublished(activation) {\n\t\treturn activation.disposal ??= (async () => {\n\t\t\ttry {\n\t\t\t\tawait activation.handle.dispose();\n\t\t\t} finally {\n\t\t\t\tthis.activations.delete(activation.childId);\n\t\t\t\tthis.releaseOwnership(activation.childId);\n\t\t\t}\n\t\t})();\n\t}\n\t/**\n\t* Register the child in a continuation-managed parent's owned set before the\n\t* child can run, so that parent cannot settle while the child is live. A\n\t* top-level or other non-continuation Agent has no Activation and stays\n\t* outside the waiting graph.\n\t*/\n\tacquireOwnership(parent, childId) {\n\t\tconst parentActivation = this.activations.get(parent.id);\n\t\tif (parentActivation === void 0) return;\n\t\tif (parentActivation.disposal !== void 0) throw new SubagentError(`subagent parent \"${parent.id}\" is being disposed; the child was not established`, \"ACTIVATION_CLOSING\");\n\t\tparentActivation.ownedChildren.add(childId);\n\t}\n\t/** Remove one child from its live owner's set and let that owner re-check settlement. */\n\treleaseOwnership(childId) {\n\t\tfor (const candidate of this.activations.values()) if (candidate.ownedChildren.delete(childId)) this.wake(candidate);\n\t}\n\t/** Let a settlement watcher re-observe quiescence after ownership or inbox changes. */\n\twake(activation) {\n\t\tactivation.poke.resolve();\n\t\tactivation.poke = Promise.withResolvers();\n\t}\n\t/**\n\t* Submit one message as the child's next FIFO turn and return its accepted\n\t* inbox id. Acceptance is the operation's success boundary; the manager owns\n\t* the Activation independently afterwards.\n\t*/\n\tsubmit(activation, content, source, parent) {\n\t\tthis.acquireOwnership(parent, activation.childId);\n\t\tconst message = createUserMessage({\n\t\t\tcontent,\n\t\t\tsource\n\t\t});\n\t\tconst accepted = this.admitWaking(activation, message.id, () => {\n\t\t\tactivation.handle.agent.followup(message);\n\t\t});\n\t\tactivation.announced = true;\n\t\treturn accepted;\n\t}\n\t/**\n\t* Account one waking send across a resident Activation's settlement window.\n\t* @param activation - Activation receiving waking inbox work.\n\t* @param messageId - stable identity of the message about to be sent.\n\t* @param send - synchronous send that publishes one enqueue occurrence.\n\t* @returns the accepted message id.\n\t*/\n\tadmitWaking(activation, messageId, send) {\n\t\tactivation.accepted.add(messageId);\n\t\ttry {\n\t\t\tsend();\n\t\t} catch (error) {\n\t\t\tactivation.accepted.delete(messageId);\n\t\t\tthrow error;\n\t\t}\n\t\tthis.wake(activation);\n\t\treturn messageId;\n\t}\n\t/**\n\t* Cross the final admission cutoff and submit without yielding. Signal abort,\n\t* manager drain, or Activation disposal that wins before this synchronous\n\t* span rejects without inbox acceptance.\n\t*/\n\tsubmitAdmitted(activation, content, source, parent, signal) {\n\t\tsignal.throwIfAborted();\n\t\tthis.assertAdmitting(parent);\n\t\t/* v8 ignore next 6 -- only a synchronous re-entrant disposer can change\n\t\t* this field between the caller's live check and this no-await boundary. */\n\t\tif (disposalOf(activation) !== void 0) throw new SubagentError(`subagent \"${activation.childId}\" activation is being disposed; the message was not accepted`, \"ACTIVATION_CLOSING\");\n\t\tthis.authorizeLineage(parent, activation.childId, activation.handle.agent.session.header.parentSession);\n\t\treturn this.submit(activation, content, source, parent);\n\t}\n\t/**\n\t* Authorize one operation against the durable direct-parent lineage. Other\n\t* agents, ancestors, teams, workflows, and hosts remain rejected until an\n\t* explicit authority protocol has a production consumer.\n\t*/\n\tauthorizeLineage(parent, childId, parentSession) {\n\t\tif (this.ctx.agents.get(parent.id) !== parent) throw new SubagentError(`subagent \"${childId}\" delivery requires the exact live parent agent`, \"UNAUTHORIZED\");\n\t\tif (parentSession !== parent.id) throw new SubagentError(`subagent \"${childId}\" belongs to another parent session`, \"UNAUTHORIZED\");\n\t}\n\t/**\n\t* Follow one Activation to settlement: wait for Agent quiescence, then for\n\t* every owned child to complete disposal, and dispose the handle once both\n\t* hold. A `next-turn` delivered while `waiting` wakes the same Agent and\n\t* returns it to `running`, so this re-observes rather than settling early.\n\t*/\n\twatchSettlement(activation) {\n\t\t(async () => {\n\t\t\twhile (disposalOf(activation) === void 0) {\n\t\t\t\tconst poked = activation.poke.promise;\n\t\t\t\tawait Promise.race([activation.handle.agent.whenIdle(), poked]);\n\t\t\t\tif (disposalOf(activation) !== void 0) return;\n\t\t\t\tconst settling = await this.locks.run(activation.childId, () => {\n\t\t\t\t\tif (disposalOf(activation) !== void 0 || this.stateOf(activation) !== \"settled\") return Promise.resolve({ settling: false });\n\t\t\t\t\treturn Promise.resolve({\n\t\t\t\t\t\tsettling: true,\n\t\t\t\t\t\tdone: this.dispose(activation)\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tif (!settling.settling) {\n\t\t\t\t\tif (activation.handle.agent.status !== \"running\") await poked;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait settling.done;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.ctx.logger.warn(`subagent \"${activation.childId}\" activation teardown failed: ${errorChain(error)}`);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t})();\n\t}\n\t/**\n\t* Stop one Activation immediately, then release it child-first. The memoized\n\t* transaction is installed before cancellation or recursive callbacks, so\n\t* admission and reentrant teardown converge on the same owner.\n\t*\n\t* The final session flush is best effort and never prevents handle disposal\n\t* or ownership release, because retaining a child would permanently pin its\n\t* ancestors in `waiting`.\n\t* @param activation - the residency epoch to stop and release.\n\t* @returns the one disposal transaction owned by this Activation.\n\t*/\n\tdispose(activation) {\n\t\tconst existing = activation.disposal;\n\t\tif (existing !== void 0) return existing;\n\t\tconst completion = Promise.withResolvers();\n\t\tactivation.disposal = completion.promise;\n\t\tthis.finishDisposal(activation).then(completion.resolve, completion.reject);\n\t\treturn completion.promise;\n\t}\n\t/**\n\t* Propagate stop synchronously, then finish the child-first release.\n\t* @param activation - the Activation whose disposal transaction is installed.\n\t* @returns once the handle and ownership edge are released.\n\t*/\n\tasync finishDisposal(activation) {\n\t\tthis.wake(activation);\n\t\tconst { childId } = activation;\n\t\tactivation.handle.agent.cancel({ kind: \"parent\" });\n\t\tconst idle = activation.handle.agent.whenIdle();\n\t\tconst childDisposals = [...activation.ownedChildren].map((child) => this.activations.get(child)).filter((child) => child !== void 0).map((child) => this.dispose(child));\n\t\tconst failures = [];\n\t\ttry {\n\t\t\tconst reasons = (await Promise.all(childDisposals.map(async (disposal) => {\n\t\t\t\ttry {\n\t\t\t\t\tawait disposal;\n\t\t\t\t\treturn;\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn error;\n\t\t\t\t}\n\t\t\t}))).filter((reason) => reason !== void 0);\n\t\t\tif (reasons.length > 0) failures.push(new SubagentError(`subagent \"${childId}\" child teardown failed: ${reasons.map((reason) => errorChain(reason)).join(\"; \")}`, \"ACTIVATION_TEARDOWN_FAILED\"));\n\t\t\tawait idle;\n\t\t\tawait this.flushFinalState(activation);\n\t\t\tactivation.observer.capture(activation.handle.agent);\n\t\t} catch (error) {\n\t\t\tfailures.push(new SubagentError(`subagent \"${childId}\" activation teardown failed: ${errorChain(error)}`, \"ACTIVATION_TEARDOWN_FAILED\", { cause: error }));\n\t\t}\n\t\ttry {\n\t\t\tawait activation.handle.dispose();\n\t\t} catch (error) {\n\t\t\tfailures.push(new SubagentError(`subagent \"${childId}\" activation handle disposal failed: ${errorChain(error)}`, \"ACTIVATION_TEARDOWN_FAILED\", { cause: error }));\n\t\t}\n\t\tlet failure;\n\t\tif (failures.length === 1) failure = failures[0];\n\t\telse if (failures.length > 1) failure = new SubagentError(`subagent \"${childId}\" activation teardown failed at ${failures.length} boundaries: ` + failures.map((item) => errorChain(item)).join(\"; \"), \"ACTIVATION_TEARDOWN_FAILED\", { cause: new AggregateError(failures) });\n\t\tthis.activations.delete(childId);\n\t\tthis.notifySettlement(activation, activation.observer.terminal(failure));\n\t\tthis.releaseOwnership(childId);\n\t\tactivation.observer.settle(failure);\n\t\tif (failure !== void 0) throw failure;\n\t}\n\t/**\n\t* Tell the durable direct parent that this child produced everything it is\n\t* going to. Unconditional for every child the caller received an id for: it\n\t* does not consider whether the child reported, because the cases that most\n\t* need it — a token ceiling, a model failure, cancellation, teardown — are\n\t* exactly the ones where the child never got to choose. A materialization\n\t* rolled back before its first acceptance stays silent, since the caller was\n\t* told that child was not established. A parent that is no longer live is not\n\t* an error; the child's own Session remains the durable record either way.\n\t* A parent whose own lineage is already closing receives the notice without a\n\t* wake, because teardown is not a reason to start a turn.\n\t*\n\t* Never blocks disposal. A delivery failure is logged and dropped, because\n\t* retaining a child to retry a notice would pin its whole ancestry in\n\t* `waiting` forever.\n\t* @param activation - the settling Activation, still owned by its parent.\n\t* @param terminal - how this epoch ended, as the terminal edge will report it.\n\t*/\n\tnotifySettlement(activation, terminal) {\n\t\tif (!activation.announced) return;\n\t\ttry {\n\t\t\tconst parent = this.ctx.agents.get(activation.parentSession);\n\t\t\tif (parent === void 0) return;\n\t\t\tconst summary = settlementSummary(activation.childId, terminal.stopReason);\n\t\t\tconst message = createUserMessage({\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: summary\n\t\t\t\t}, ...terminal.output === void 0 ? [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: \"It left no closing message.\"\n\t\t\t\t}] : [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: \"Its closing message:\"\n\t\t\t\t}, ...terminal.output]],\n\t\t\t\tsource: {\n\t\t\t\t\tkind: \"subagent-settled\",\n\t\t\t\t\tform: \"notice\",\n\t\t\t\t\tsummary: boundContextSummary(summary),\n\t\t\t\t\tsenderSessionId: activation.childId\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (this.closingTeardownFor(parent) !== void 0) {\n\t\t\t\tparent.inject(message);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.sendWaking(parent, message, () => {\n\t\t\t\tif (parent.status === \"idle\") parent.followup(message);\n\t\t\t\telse parent.steer(message);\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.ctx.logger.warn(`subagent \"${activation.childId}\" settlement notice was not delivered to its parent: ` + errorChain(error));\n\t\t}\n\t}\n\t/**\n\t* Request a best-effort final session flush after the child is quiescent.\n\t* Listener failure is logged because flush participation cannot identify a\n\t* particular persistence backend, and teardown must still release ownership.\n\t* @param activation - the Activation whose final events should be flushed.\n\t*/\n\tasync flushFinalState(activation) {\n\t\tconst child = activation.handle.agent;\n\t\ttry {\n\t\t\tawait child.ctx.sessions.flush(child.session);\n\t\t} catch (error) {\n\t\t\tthis.ctx.logger.warn(`subagent \"${activation.childId}\" best-effort final session flush failed; the persisted state may be unavailable or stale on resume: ${errorChain(error)}`);\n\t\t}\n\t}\n\t/** Resolve the persistence service continuable children require, or fail loud. */\n\trequirePersistence() {\n\t\tconst persistence = this.ctx.get(\"sessionPersistence\");\n\t\tif (persistence === void 0) throw new SubagentError(\"continuable subagents require session persistence (load a dsh-session-persistence backend)\", \"PERSISTENCE_UNAVAILABLE\");\n\t\treturn persistence;\n\t}\n};\n//#endregion\n//#region lib/types/activation-setup-registry.js\n/**\n* Internal registry of deployment capabilities composed into every continuable\n* child's unpublished creation context.\n*\n* A contribution grants a child-scoped capability without teaching the\n* continuation manager which capabilities exist. The manager owns residency;\n* this registry owns the join between plugin lifetime, unpublished setup, and\n* Activation disposal, so no installation outlives either owner and no removed\n* contribution can be installed after revocation reports completion.\n*\n* @module @deepseek-ai/dsh-subagent/activation-setup-registry\n*/\n/** Re-read mutable removal state after a contribution may have revoked itself. */\nfunction isRemoved(registration) {\n\treturn registration.removed;\n}\n/**\n* Owns continuable-child setup registrations, installations, rollback, child\n* cleanup, and immediate live revocation.\n*/\nvar SubagentActivationSetupRegistry = class {\n\t/** Live contributions in installation order. */\n\tregistrations = /* @__PURE__ */ new Set();\n\t/** Child context to its live installations. */\n\tbyChild = /* @__PURE__ */ new Map();\n\t/**\n\t* Register one contribution.\n\t* @param contribution - synchronous child-scope installer.\n\t* @returns an idempotent registration undo.\n\t* @throws after attempting every installation when any disposer fails.\n\t*/\n\tregister(contribution) {\n\t\tconst registration = {\n\t\t\tcontribution,\n\t\t\tremoved: false,\n\t\t\tinstallations: /* @__PURE__ */ new Set()\n\t\t};\n\t\tthis.registrations.add(registration);\n\t\treturn () => {\n\t\t\tif (registration.removed) return;\n\t\t\tregistration.removed = true;\n\t\t\tthis.registrations.delete(registration);\n\t\t\tthis.releaseAll([...registration.installations], \"contribution removal\");\n\t\t};\n\t}\n\t/**\n\t* Install every live contribution into one unpublished child context.\n\t* @param childCtx - the child's unpublished scoped context.\n\t* @returns the provisioning commit consumed at Agent publication.\n\t*/\n\tapply(childCtx) {\n\t\tconst state = {\n\t\t\tinstallations: [],\n\t\t\tinvalidated: false\n\t\t};\n\t\ttry {\n\t\t\tfor (const registration of [...this.registrations]) {\n\t\t\t\t/* v8 ignore next -- only a synchronous re-entrant revocation of an\n\t\t\t\t* already-snapshotted registration reaches this guard. */\n\t\t\t\tif (registration.removed) continue;\n\t\t\t\tconst installation = {\n\t\t\t\t\tregistration,\n\t\t\t\t\tchildCtx,\n\t\t\t\t\tdispose: registration.contribution(childCtx),\n\t\t\t\t\treleased: false,\n\t\t\t\t\ttransaction: state\n\t\t\t\t};\n\t\t\t\tregistration.installations.add(installation);\n\t\t\t\tstate.installations.push(installation);\n\t\t\t\tlet indexed = this.byChild.get(childCtx);\n\t\t\t\tif (indexed === void 0) {\n\t\t\t\t\tindexed = /* @__PURE__ */ new Set();\n\t\t\t\t\tthis.byChild.set(childCtx, indexed);\n\t\t\t\t}\n\t\t\t\tindexed.add(installation);\n\t\t\t\tif (isRemoved(registration)) this.release(installation);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tthis.releaseAll([...state.installations], \"setup rollback\");\n\t\t\t} catch (releaseFailure) {}\n\t\t\tthrow error;\n\t\t}\n\t\tchildCtx.effect(() => () => {\n\t\t\tthis.releaseChild(childCtx);\n\t\t}, \"subagents.activationSetup()\");\n\t\treturn { commit: () => {\n\t\t\tif (state.invalidated) throw new SubagentError(\"a continuable-subagent setup contribution was revoked while this child was being built; the child was not established\", \"ACTIVATION_SETUP_REVOKED\");\n\t\t\tfor (const installation of state.installations) installation.transaction = void 0;\n\t\t} };\n\t}\n\t/** Release every remaining installation owned by one disposed child scope. */\n\treleaseChild(childCtx) {\n\t\tconst indexed = this.byChild.get(childCtx) ?? [];\n\t\tthis.releaseAll([...indexed], \"child scope disposal\");\n\t}\n\t/**\n\t* Release a batch completely before reporting disposer failures.\n\t* @param installations - records to release.\n\t* @param during - operation name for diagnostics.\n\t*/\n\treleaseAll(installations, during) {\n\t\tconst failures = [];\n\t\tfor (const installation of installations) try {\n\t\t\tthis.release(installation);\n\t\t} catch (error) {\n\t\t\tfailures.push(error);\n\t\t}\n\t\tif (failures.length === 0) return;\n\t\tthrow new SubagentError(`continuable-subagent setup ${during} failed to release ${failures.length} installation(s): ` + failures.map((failure) => errorChain(failure)).join(\"; \"), \"ACTIVATION_SETUP_RELEASE_FAILED\");\n\t}\n\t/** Drop one installation from both indices and dispose it exactly once. */\n\trelease(installation) {\n\t\tif (installation.released) return;\n\t\tinstallation.released = true;\n\t\tinstallation.registration.installations.delete(installation);\n\t\tconst indexed = this.byChild.get(installation.childCtx);\n\t\t/* v8 ignore next 4 -- every live installation is indexed until this method removes it. */\n\t\tif (indexed !== void 0) {\n\t\t\tindexed.delete(installation);\n\t\t\tif (indexed.size === 0) this.byChild.delete(installation.childCtx);\n\t\t}\n\t\tif (installation.transaction !== void 0) installation.transaction.invalidated = true;\n\t\tinstallation.dispose();\n\t}\n};\n//#endregion\n//#region lib/types/list-children.js\n/**\n* Read-only enumeration of durable subagent children and descendant trees\n* straight from the live session store and optional session persistence — no\n* query service. Candidates come from one live-preferred corpus; each child's\n* mode/label is the registered `subagent` projection unit's value, resolved\n* down a three-rung ladder: the registry's watermark cache for a live child,\n* a durable projection-cache row when it serves an own-suffix identity (the\n* seq gate), and one persistence inspection folded through the registry\n* otherwise, validated against the enumerated lifecycle. The projection fold\n* is the single classification authority — this module parses no descriptor\n* itself. Absent persistence, enumeration is live-only: a cold child is\n* unreachable for resume anyway, so its absence is capability absence, not an\n* error. The module owns no catalog state and does not consult Activation,\n* Agent-registry, continuation-manager, or provider state.\n*\n* @module @deepseek-ai/dsh-subagent\n*/\n/**\n* Concurrent cold inspections per listing; a constant because it bounds one\n* read-only scan of local media, not deployment behavior. Should a networked\n* persistence backend appear, promote it to a validated `Config` field.\n*/\nconst COLD_READ_CONCURRENCY = 4;\n/**\n* Enumerate one parent's origin-classified direct children from the\n* live-preferred merge of `ctx.sessions` and optional session persistence,\n* serving each identity from the `subagent` projection unit: the registry's\n* watermark snapshot for a live child; for a cold one, a durable\n* projection-cache row when it serves an own-suffix identity (the seq gate),\n* else one bounded-concurrency persistence inspection folded through the\n* registry.\n* @see SubagentRuntime.listChildren for the public cancellation and failure contract.\n* @param ctx - context carrying the session store, the projection registry,\n* optional persistence, and the optional projection cache.\n* @param parentSessionId - parent session whose direct children are listed.\n* @param signal - caller-owned cancellation observed around every persistence read.\n* @returns children and per-child diagnostics ordered by `createdAt`, then id.\n* @throws {@link SubagentError} when the projection registry or the session\n* store is not mounted, or the caller cancels the listing.\n*/\nasync function listChildren(ctx, parentSessionId, signal) {\n\tconst listing = await prepareListing(ctx, signal);\n\treturn (await resolveCandidateRows([...listing.corpus.values()].filter((record) => record.header.parentSession === parentSessionId && record.header.origin === \"subagent\").sort(compareCorpusRecords), listing, signal)).filter((row) => row !== void 0);\n}\n/**\n* Enumerate every session-backed subagent below one root in stable pre-order.\n* Ordinary sessions and one-shot children remain traversal nodes, so a\n* continuable child below either is still discovered. Classification uses the\n* same projection-backed runtime as {@link listChildren}; no Agent is loaded or\n* resumed.\n* @see SubagentRuntime.listDescendants for the public cancellation and failure contract.\n* @param ctx - context carrying the session store, projection registry, and optional persistence/cache.\n* @param rootSessionId - session whose complete descendant tree is listed.\n* @param signal - caller-owned cancellation observed around every persistence read.\n* @returns interpreted subagents with durable direct-parent and root-relative depth.\n* @throws {@link SubagentError} under the same conditions as {@link listChildren}.\n*/\nasync function listDescendants(ctx, rootSessionId, signal) {\n\tconst listing = await prepareListing(ctx, signal);\n\tconst positioned = descendantCandidates(listing.corpus, rootSessionId);\n\tconst rows = await resolveCandidateRows(positioned.map((candidate) => candidate.record), listing, signal);\n\tconst entries = [];\n\tpositioned.forEach((position, index) => {\n\t\tconst row = rows[index];\n\t\tif (row !== void 0) entries.push({\n\t\t\t...row,\n\t\t\tparentId: position.parentId,\n\t\t\tdepth: position.depth\n\t\t});\n\t});\n\treturn entries;\n}\n/** Resolve listing services once and build one live-preferred session corpus. */\nasync function prepareListing(ctx, signal) {\n\tconst projections = ctx.get(\"sessionProjections\");\n\tif (projections === void 0) throw new SubagentError(\"listing subagents requires the sessionProjections registry (load @deepseek-ai/dsh-session-projection)\", \"SUBAGENT_CONTROL_PROJECTIONS_UNAVAILABLE\");\n\tconst sessions = ctx.get(\"sessions\");\n\tif (sessions === void 0) throw new SubagentError(\"listing subagents requires the session store (load @deepseek-ai/dsh-session)\", \"SUBAGENT_CONTROL_SESSION_STORE_UNAVAILABLE\");\n\tassertListingNotCancelled(signal);\n\tconst persistence = ctx.get(\"sessionPersistence\");\n\tconst cache = ctx.get(\"sessionProjectionCache\");\n\tlet persistedHeaders = [];\n\tif (persistence !== void 0) {\n\t\ttry {\n\t\t\tpersistedHeaders = await persistence.list(signal);\n\t\t} catch (error) {\n\t\t\tassertListingNotCancelled(signal);\n\t\t\tthrow error;\n\t\t}\n\t\tassertListingNotCancelled(signal);\n\t}\n\tconst corpus = /* @__PURE__ */ new Map();\n\tfor (const header of persistedHeaders) corpus.set(header.id, {\n\t\theader,\n\t\tlive: void 0\n\t});\n\tfor (const session of sessions.list()) corpus.set(session.header.id, {\n\t\theader: session.header,\n\t\tlive: session\n\t});\n\tconst subagentParents = /* @__PURE__ */ new Set();\n\tfor (const record of corpus.values()) if (record.header.origin === \"subagent\" && record.header.parentSession !== void 0) subagentParents.add(record.header.parentSession);\n\treturn {\n\t\tprojections,\n\t\tpersistence,\n\t\tcache,\n\t\tcorpus,\n\t\tsubagentParents\n\t};\n}\n/** Resolve projection-backed rows for aligned candidates with bounded cold reads. */\nasync function resolveCandidateRows(candidates, listing, signal) {\n\tconst { projections, persistence, cache, subagentParents } = listing;\n\tconst rows = Array.from({ length: candidates.length });\n\tconst coldReads = [];\n\tcandidates.forEach((candidate, index) => {\n\t\tconst childId = candidate.header.id;\n\t\tif (candidate.live === void 0) {\n\t\t\tcoldReads.push({\n\t\t\t\tindex,\n\t\t\t\theader: candidate.header\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tlet identity;\n\t\ttry {\n\t\t\tidentity = projections.snapshot(candidate.live).values.subagent;\n\t\t} catch {\n\t\t\trows[index] = {\n\t\t\t\tkind: \"diagnostic\",\n\t\t\t\tid: childId,\n\t\t\t\treason: \"corrupt\"\n\t\t\t};\n\t\t\treturn;\n\t\t}\n\t\tif (identity === void 0 || identity === null) return;\n\t\trows[index] = childRow(childId, identity, \"running\", subagentParents.has(childId));\n\t});\n\tif (persistence !== void 0 && coldReads.length > 0) {\n\t\tconst queue = [...coldReads];\n\t\tawait Promise.all(Array.from({ length: Math.min(COLD_READ_CONCURRENCY, queue.length) }, async () => {\n\t\t\tfor (let job = queue.shift(); job !== void 0; job = queue.shift()) rows[job.index] = await resolveColdIdentity(persistence, projections, cache, job.header, subagentParents.has(job.header.id), signal);\n\t\t}));\n\t}\n\tassertListingNotCancelled(signal);\n\treturn rows;\n}\n/** Build origin-classified candidates from the complete tree without recursion. */\nfunction descendantCandidates(corpus, rootSessionId) {\n\tconst children = /* @__PURE__ */ new Map();\n\tfor (const record of corpus.values()) {\n\t\tconst parentId = record.header.parentSession;\n\t\tif (parentId === void 0) continue;\n\t\tconst siblings = children.get(parentId);\n\t\tif (siblings === void 0) children.set(parentId, [record]);\n\t\telse siblings.push(record);\n\t}\n\tfor (const siblings of children.values()) siblings.sort(compareCorpusRecords);\n\tconst positioned = [];\n\tconst stack = (children.get(rootSessionId) ?? []).map((record) => ({\n\t\trecord,\n\t\tparentId: rootSessionId,\n\t\tdepth: 1\n\t})).reverse();\n\tconst visited = new Set([rootSessionId]);\n\twhile (stack.length > 0) {\n\t\tconst position = stack.pop();\n\t\tconst id = position.record.header.id;\n\t\tif (visited.has(id)) continue;\n\t\tvisited.add(id);\n\t\tif (position.record.header.origin === \"subagent\") positioned.push(position);\n\t\tconst descendants = children.get(id) ?? [];\n\t\tfor (const record of [...descendants].reverse()) stack.push({\n\t\t\trecord,\n\t\t\tparentId: id,\n\t\t\tdepth: position.depth + 1\n\t\t});\n\t}\n\treturn positioned;\n}\n/** Compare siblings by durable creation time, then id. */\nfunction compareCorpusRecords(a, b) {\n\treturn a.header.createdAt - b.header.createdAt || a.header.id.localeCompare(b.header.id);\n}\n/**\n* Resolve one cold candidate down the remaining ladder: a durable\n* projection-cache row when it serves an own-suffix identity (the seq gate),\n* otherwise one persistence inspection folded through the projection\n* registry (the same detached recipe the API proxy uses for detached session\n* projections). A failed inspection is one transient `unavailable` row\n* retried on the next listing; an inspection naming another lifecycle, and a\n* settled log the fold cannot identify — or that makes any registered unit\n* throw — are final, so they report `corrupt`.\n*/\nasync function resolveColdIdentity(persistence, projections, cache, header, hasChildren, signal) {\n\tconst childId = header.id;\n\tif (cache !== void 0) {\n\t\tlet cached;\n\t\ttry {\n\t\t\tcached = cache.cachedSnapshot(header)?.values.subagent;\n\t\t} catch {\n\t\t\tcached = void 0;\n\t\t}\n\t\tif (cached !== void 0 && cached !== null && cached.seq >= (header.seedLength ?? 0)) return childRow(childId, cached, \"inactive\", hasChildren);\n\t}\n\tassertListingNotCancelled(signal);\n\tlet inspected;\n\ttry {\n\t\tinspected = await persistence.inspect(childId, signal);\n\t} catch {\n\t\tassertListingNotCancelled(signal);\n\t\treturn {\n\t\t\tkind: \"diagnostic\",\n\t\t\tid: childId,\n\t\t\treason: \"unavailable\"\n\t\t};\n\t}\n\tassertListingNotCancelled(signal);\n\tif (!sameLifecycle(inspected.meta, header)) return {\n\t\tkind: \"diagnostic\",\n\t\tid: childId,\n\t\treason: \"corrupt\"\n\t};\n\tlet identity;\n\ttry {\n\t\tidentity = projections.restore({}, inspected.events, 0).snapshot.values.subagent;\n\t} catch {\n\t\treturn {\n\t\t\tkind: \"diagnostic\",\n\t\t\tid: childId,\n\t\t\treason: \"corrupt\"\n\t\t};\n\t}\n\tif (identity === void 0 || identity === null) return {\n\t\tkind: \"diagnostic\",\n\t\tid: childId,\n\t\treason: \"corrupt\"\n\t};\n\treturn childRow(childId, identity, \"inactive\", hasChildren);\n}\n/** Materialize one served identity as its child row. */\nfunction childRow(id, identity, activity, hasChildren) {\n\treturn identity.mode === \"one-shot\" ? {\n\t\tkind: \"child\",\n\t\tid,\n\t\tmode: \"one-shot\",\n\t\t...identity.label !== void 0 ? { label: identity.label } : {},\n\t\tactivity,\n\t\thasChildren\n\t} : {\n\t\tkind: \"child\",\n\t\tid,\n\t\tmode: \"continuable\",\n\t\tlabel: identity.label,\n\t\tactivity,\n\t\thasChildren\n\t};\n}\n/** Immutable header fields that distinguish one session lifecycle from another under the same id. */\nconst LIFECYCLE_WITNESS_KEYS = [\n\t\"version\",\n\t\"id\",\n\t\"createdAt\",\n\t\"cwd\",\n\t\"parentSession\",\n\t\"seedLength\",\n\t\"delegationDepth\"\n];\n/** Whether an inspected log still belongs to the enumerated lifecycle. */\nfunction sameLifecycle(meta, expected) {\n\treturn LIFECYCLE_WITNESS_KEYS.every((key) => meta[key] === expected[key]);\n}\n/** Stop a listing at its next cancellation checkpoint. */\nfunction assertListingNotCancelled(signal) {\n\tif (signal?.aborted) throw new SubagentError(\"subagent listing was cancelled\", \"CANCELLED\");\n}\n/**\n* Fold turn boundaries around the child's own durable descriptor.\n*\n* A fork seed may contain an ancestor descriptor and completed turns. Every\n* descriptor therefore resets the accumulated state; the healthy catalog\n* admits only a child with exactly one descriptor in its own suffix, making\n* the final reset the child's authoritative timing origin.\n*/\nconst subagentTimingProjectionDefinition = {\n\tkey: \"subagentTiming\",\n\tschema: z.object({\n\t\tsettledMs: z.number().int().nonnegative(),\n\t\tactive: z.object({\n\t\t\tsince: z.number().int().nonnegative(),\n\t\t\tthrough: z.number().int().nonnegative()\n\t\t}).strict().optional()\n\t}).strict(),\n\tinit: () => ({\n\t\tdescriptorSeen: false,\n\t\tsettledMs: 0\n\t}),\n\tapply: (state, event) => {\n\t\tif (event.type === \"turn/start\") return state.descriptorSeen ? {\n\t\t\t...state,\n\t\t\tactive: {\n\t\t\t\tsince: event.time,\n\t\t\t\tthrough: event.time\n\t\t\t}\n\t\t} : {\n\t\t\t...state,\n\t\t\tpendingTurnStart: event.time\n\t\t};\n\t\tif (event.type === \"subagent/descriptor\") {\n\t\t\tconst activeSince = state.active?.since ?? state.pendingTurnStart;\n\t\t\treturn {\n\t\t\t\tdescriptorSeen: true,\n\t\t\t\tsettledMs: 0,\n\t\t\t\t...activeSince === void 0 ? {} : { active: {\n\t\t\t\t\tsince: activeSince,\n\t\t\t\t\tthrough: event.time\n\t\t\t\t} }\n\t\t\t};\n\t\t}\n\t\tif (event.type === \"turn/end\") {\n\t\t\tif (!state.descriptorSeen) {\n\t\t\t\tif (state.pendingTurnStart === void 0) return state;\n\t\t\t\tconst { pendingTurnStart: _closed, ...next } = state;\n\t\t\t\treturn next;\n\t\t\t}\n\t\t\tif (state.active === void 0) return state;\n\t\t\tconst { active, ...rest } = state;\n\t\t\treturn {\n\t\t\t\t...rest,\n\t\t\t\tsettledMs: state.settledMs + Math.max(0, event.time - active.since)\n\t\t\t};\n\t\t}\n\t\tif (state.active === void 0) return state;\n\t\treturn {\n\t\t\t...state,\n\t\t\tactive: {\n\t\t\t\t...state.active,\n\t\t\t\tthrough: event.time\n\t\t\t}\n\t\t};\n\t},\n\tview: (state) => ({\n\t\tsettledMs: state.settledMs,\n\t\t...state.active === void 0 ? {} : { active: state.active }\n\t}),\n\tstateVersion: 2\n};\nconst identitySchema = z.discriminatedUnion(\"mode\", [z.object({\n\tmode: z.literal(\"one-shot\"),\n\tlabel: z.string().optional(),\n\tseq: z.number().int().nonnegative()\n}).strict(), z.object({\n\tmode: z.literal(\"continuable\"),\n\tlabel: z.string(),\n\tseq: z.number().int().nonnegative()\n}).strict()]).nullable();\n/** Interpret one `subagent/descriptor` event's identity; no value when the payload cannot be trusted. */\nfunction descriptorIdentity(event) {\n\tlet descriptor;\n\ttry {\n\t\tdescriptor = foldSubagentDescriptor([event]);\n\t} catch {\n\t\tdescriptor = void 0;\n\t}\n\tif (descriptor === void 0) return void 0;\n\treturn descriptor.mode === \"one-shot\" ? {\n\t\tmode: \"one-shot\",\n\t\t...descriptor.label !== void 0 ? { label: descriptor.label } : {},\n\t\tseq: event.seq\n\t} : {\n\t\tmode: \"continuable\",\n\t\tlabel: descriptor.label,\n\t\tseq: event.seq\n\t};\n}\n/**\n* Fold the durable mode/label identity from `subagent/descriptor` events,\n* last-wins: a fork seed may replay an ancestor's descriptor, and the child's\n* own descriptor must override it — the same reset discipline as\n* {@link subagentTimingProjectionDefinition}. A malformed or unknown-version\n* payload resets to the `null` sentinel instead of throwing, so a fork of a\n* healthy ancestor never inherits an identity its own descriptor failed to\n* establish — and the reset survives every JSON push frame, so a consumer\n* holding the earlier identity replaces it instead of keeping it stale;\n* `null` ⟺ no valid descriptor, with the causes deliberately undistinguished.\n*/\nconst subagentIdentityProjectionDefinition = {\n\tkey: \"subagent\",\n\tschema: identitySchema,\n\tinit: () => ({}),\n\tapply: (state, event) => {\n\t\tif (event.type !== \"subagent/descriptor\") return state;\n\t\tconst identity = descriptorIdentity(event);\n\t\treturn identity === void 0 ? {} : { identity };\n\t},\n\tview: (state) => state.identity ?? null,\n\tstateVersion: 2\n};\n//#endregion\n//#region lib/types/out-of-process.js\n/**\n* Provider-side vocabulary for OUT-OF-PROCESS subagent backends — the pieces\n* that enforce this seam's own contracts around a child in another process:\n* the no-capabilities advertisement, timing-bound validation, child\n* working-directory resolution (config override, else the delegating parent\n* session's workspace), the never-reject result settlement, and the standard\n* run-handle publication. Backends compose these with their own wire drivers;\n* the process machinery itself (spawn, env scrub, tree-scoped teardown)\n* belongs to the `dsh-subprocess` seam.\n*\n* @module @deepseek-ai/dsh-subagent/out-of-process\n*/\n/**\n* The capability advertisement of an out-of-process backend: NONE. A child in\n* another process cannot honor parent-enforced start features\n* (`outputSchema`/`maxDepth`/`toolFilter`/`persona`), so the service rejects a\n* request needing any of them before `start` runs — never accepted-then-ignored.\n*/\nconst NO_START_CAPABILITIES = Object.freeze({\n\toutputSchema: false,\n\tdepthLimit: false,\n\ttoolFilter: false,\n\tpersona: false\n});\n/**\n* Assert a configured timing bound is a positive finite number (it bounds a\n* teardown or shutdown wait; zero, negative, or NaN would skip or wedge it).\n* @param prefix - the consuming plugin's diagnostic prefix (e.g. `subagent-acp`).\n* @param name - the config field name, for the diagnostic.\n* @param value - the configured value.\n*/\nfunction assertPositiveFinite(prefix, name, value) {\n\tif (!Number.isFinite(value) || value <= 0) throw new Error(`${prefix}: ${name} must be a positive finite number`);\n}\n/**\n* Whether `path` names an existing directory the harness can ENTER. The\n* search-permission probe matters: `statSync().isDirectory()` is true for a\n* mode-600 directory, but a subprocess cwd needs `X_OK` or spawn fails EACCES.\n*/\nfunction isEnterableDirectory(path) {\n\ttry {\n\t\tif (!statSync(path).isDirectory()) return false;\n\t\taccessSync(path, constants.X_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Assert `cwd` can actually host the child: absolute (it doubles as the\n* child's workspace identity, and a relative path would be re-anchored to the\n* server process's launch directory) and an existing directory (fail here,\n* before the process boundary, instead of as an ambiguous spawn ENOENT).\n* @param prefix - the consuming plugin's diagnostic prefix.\n* @param label - which source supplied the value, for the diagnostic.\n* @param cwd - the candidate working directory.\n* @returns `cwd`, validated.\n*/\nfunction assertUsableCwd(prefix, label, cwd) {\n\tif (!isAbsolute(cwd)) throw new Error(`${prefix}: ${label} must be an absolute path: ${cwd}`);\n\tif (!isEnterableDirectory(cwd)) throw new Error(`${prefix}: ${label} is not an accessible directory: ${cwd}`);\n\treturn cwd;\n}\n/**\n* Validate a configured `cwd` override ONCE, at plugin load: reject the empty\n* string (`path.resolve('')` is the process cwd — it would silently\n* reintroduce the launch-directory fallback this resolution removes),\n* interpret a relative path against the harness launch directory, and require\n* an enterable directory.\n* @param prefix - the consuming plugin's diagnostic prefix.\n* @param cwd - the configured override, or `undefined` when the config omits it.\n* @returns the validated absolute override, or `undefined` when omitted.\n*/\nfunction validateConfiguredCwd(prefix, cwd) {\n\tif (cwd === void 0) return void 0;\n\tif (cwd === \"\") throw new Error(`${prefix}: config cwd must not be empty — omit the key to inherit the parent session cwd`);\n\treturn assertUsableCwd(prefix, \"config cwd\", resolve(cwd));\n}\n/**\n* Resolve the child's working directory at start: the deployment override\n* when configured (already validated at load), else the parent session's\n* workspace cwd (validated here, its earliest resolvable point). Fails loud\n* when neither exists — falling back to the harness process cwd would\n* silently bind the child to the server's launch directory instead of the\n* delegating session's workspace (one server process serves many sessions,\n* each with its own cwd).\n* @param prefix - the consuming plugin's diagnostic prefix.\n* @param configured - the load-validated override, or `undefined`.\n* @param parentCwd - the delegating parent session's workspace cwd, if any.\n* @returns the absolute child working directory.\n*/\nfunction resolveChildCwd(prefix, configured, parentCwd) {\n\tif (configured !== void 0) return configured;\n\tif (parentCwd === void 0) throw new Error(`${prefix}: no working directory for the child — configure \\`cwd\\` or delegate from a parent session that has one`);\n\treturn assertUsableCwd(prefix, \"parent session cwd\", parentCwd);\n}\n/** Normalize an unknown thrown value to an Error (the catch binding is `unknown`). */\nfunction toError(value) {\n\t/* v8 ignore next */\n\treturn value instanceof Error ? value : new Error(String(value));\n}\n/**\n* Settle an out-of-process run result under the seam contract: `result` never\n* rejects after publication. A normally completed or rejected attempt resolves\n* as `aborted` when cancellation already settled locally; another rejection is\n* flattened to `stopReason: 'error'` through the contained diagnostic sink.\n* The abort listener is removed on every path.\n* @param parts - the attempt, output snapshot, cancellation state, sink, and signal wiring.\n* @returns the terminal result (never a rejection).\n*/\nasync function settleRunResult(parts) {\n\ttry {\n\t\tconst result = await parts.attempt();\n\t\treturn parts.cancelled() ? {\n\t\t\toutput: parts.collectOutput(),\n\t\t\tstopReason: \"aborted\"\n\t\t} : result;\n\t} catch (error) {\n\t\tif (parts.cancelled()) return {\n\t\t\toutput: parts.collectOutput(),\n\t\t\tstopReason: \"aborted\"\n\t\t};\n\t\ttry {\n\t\t\tparts.onError?.(toError(error), \"error\");\n\t\t} catch {}\n\t\treturn {\n\t\t\toutput: parts.collectOutput(),\n\t\t\tstopReason: \"error\"\n\t\t};\n\t} finally {\n\t\tparts.signal.removeEventListener(\"abort\", parts.onAbort);\n\t}\n}\n/**\n* Publish the seam run handle for an out-of-process child. `dispose()` is\n* idempotent (one memoized teardown): it removes the abort listener, settles\n* local cancellation — there is no assumption the child cooperates — and then\n* awaits the backend's teardown to actual exit.\n* @param parts - the run identity, result, cancellation wiring, and teardown.\n* @returns the seam run handle (`localAgent` is `undefined` for remote runs).\n*/\nfunction subprocessRunHandle(parts) {\n\tlet disposal;\n\treturn {\n\t\tid: parts.id,\n\t\tlocalAgent: void 0,\n\t\tresult: parts.result,\n\t\tdispose() {\n\t\t\tif (disposal !== void 0) return disposal;\n\t\t\tparts.signal.removeEventListener(\"abort\", parts.onAbort);\n\t\t\tparts.requestCancel();\n\t\t\tdisposal = parts.teardown();\n\t\t\treturn disposal;\n\t\t}\n\t};\n}\n//#endregion\n//#region lib/types/run-settlement.js\n/**\n* Settlement of one ONE-SHOT subagent run into a background-Task outcome. Only\n* the one-shot background path uses Jobs; continuable children have no Task,\n* no per-message result, and no Task cancellation.\n*\n* @module @deepseek-ai/dsh-subagent/run-settlement\n*/\n/** Flatten a child's final output blocks to the task's final text. */\nfunction finalText(blocks) {\n\treturn blocks.filter((block) => block.type === \"text\").map((block) => block.text).join(\"\");\n}\n/**\n* Map a child result to the task outcome: completed carries final text,\n* aborted is killed, and every other reason is failed without partial output.\n* @param result - child terminal result.\n* @returns outcome for the `ctx.jobs` registration.\n*/\nfunction runOutcome(result) {\n\tswitch (result.stopReason) {\n\t\tcase \"completed\": return {\n\t\t\tstatus: \"completed\",\n\t\t\toutput: finalText(result.output)\n\t\t};\n\t\tcase \"aborted\": return { status: \"killed\" };\n\t\tcase \"error\":\n\t\tcase \"max-tokens\":\n\t\tcase \"refusal\": return {\n\t\t\tstatus: \"failed\",\n\t\t\tdetail: result.stopReason\n\t\t};\n\t\tdefault: return {\n\t\t\tstatus: \"failed\",\n\t\t\tdetail: String(result.stopReason)\n\t\t};\n\t}\n}\n/**\n* Await the child result, dispose the run, then return its task outcome. Result\n* and disposal failures become `failed`; when both fail, both details survive.\n* @param run - live run to settle and release.\n* @returns outcome after child resources are released.\n*/\nasync function settleRun(run) {\n\tlet outcome;\n\ttry {\n\t\toutcome = runOutcome(await run.result);\n\t} catch (error) {\n\t\toutcome = {\n\t\t\tstatus: \"failed\",\n\t\t\tdetail: String(error)\n\t\t};\n\t}\n\ttry {\n\t\tawait run.dispose();\n\t} catch (error) {\n\t\treturn {\n\t\t\tstatus: \"failed\",\n\t\t\tdetail: `${outcome.detail === void 0 ? \"\" : `${outcome.detail}; `}dispose failed: ${String(error)}`\n\t\t};\n\t}\n\treturn outcome;\n}\n//#endregion\n//#region lib/types/index.js\n/**\n* Service Definition for the subagent capability seam (`ctx.subagents`): a named-provider registry plus a\n* capability-validating asynchronous start API. Providers establish a\n* child before returning its run, so fulfillment is the single publication and\n* ownership-transfer boundary.\n*\n* Unlike the bash seam (one executor per context, second load throws), MULTIPLE\n* providers coexist here: each registers under a unique name and a caller picks\n* one by name. The shape mirrors the LLM adapter registry\n* (`LlmRuntime.registerAdapter`), not the single-service bash executor.\n*\n* This package owns the Service Definition role of the capability seam. Service Providers\n* (`@deepseek-ai/dsh-subagent-spawn-in-process`, `-fork`, `-acp`) and the model-facing\n* consumer (`@deepseek-ai/dsh-tool-subagent`) are separate packages.\n*\n* Public operations express caller intent: `start` returns one published owned\n* one-shot run, `startContinuable` establishes a durable continuable child, and\n* `followup` delivers later content without exposing whether the child is\n* resident. Continuable children never become a {@link SubagentRun}: the\n* continuation manager holds their `AgentHandle` directly and orders every turn\n* through the child's own inbox, so providers contribute only the detached\n* creation spec and see no handle, turn, or teardown. Child and descendant\n* discovery read the live session store and optional session persistence\n* directly and do not require that continuation runtime.\n*\n* Same-process providers are trusted typed collaborators. Requests, provider\n* descriptors, results, and lifecycle payloads are borrowed immutable values;\n* serialization and hostile-input validation belong at real process, worker,\n* persistence, and model boundaries.\n*\n* @module @deepseek-ai/dsh-subagent\n*/\n/** Named provider registry with one-shot runs, durable discovery, and continuable-child operations. */\nvar SubagentRuntime = class extends Service {\n\tproviders = /* @__PURE__ */ new Map();\n\tcontinuations;\n\t/** Deployment contributions composed into unpublished continuable children. */\n\tsetupRegistry = new SubagentActivationSetupRegistry();\n\t/**\n\t* The contained lifecycle-edge publisher. Built here because scoped dispatch\n\t* keys its carrier by this exact service instance, whose own context filter\n\t* composes into the carrier.\n\t*/\n\temitLifecycle;\n\tconstructor(ctx) {\n\t\tsuper(ctx, \"subagents\");\n\t\tthis.emitLifecycle = createLifecycleEmitter(this.ctx, (parent) => scopeTarget(this, parent));\n\t\tctx.inject([\"agents\"], (childCtx) => {\n\t\t\tconst manager = new SubagentContinuationManager(childCtx, {\n\t\t\t\tprepareContinuable: (name, request) => this.prepareContinuable(name, request),\n\t\t\t\tobserveActivation: (provider, childId, parent) => this.observeActivation(provider, childId, parent)\n\t\t\t}, this.setupRegistry);\n\t\t\tthis.continuations = manager;\n\t\t\tchildCtx.effect(() => () => {\n\t\t\t\t/* v8 ignore else -- one injected binding owns the slot until its fiber disposes. */\n\t\t\t\tif (this.continuations === manager) this.continuations = void 0;\n\t\t\t}, \"subagents.continuationBinding()\");\n\t\t});\n\t\tctx.inject([\"sessionProjections\"], (projectionCtx) => {\n\t\t\tprojectionCtx.sessionProjections.register(subagentTimingProjectionDefinition);\n\t\t\tprojectionCtx.sessionProjections.register(subagentIdentityProjectionDefinition);\n\t\t});\n\t}\n\t/**\n\t* Establish one durable continuable child and deliver its initial prompt.\n\t* Resolves when the child's inbox accepts that prompt, without waiting for the\n\t* turn to start or for the message to reach the Session log; any earlier\n\t* failure rejects with no ids and rolls back the child entirely.\n\t* @param spec - provider, delegation request, and caller cancellation.\n\t* @returns the durable child id and the accepted prompt's message id.\n\t* @throws when continuation services are unavailable or materialization fails.\n\t*/\n\tasync startContinuable(spec) {\n\t\treturn this.requireContinuations().startContinuable(spec);\n\t}\n\t/**\n\t* Deliver one later message to a continuable child as its next FIFO turn. A\n\t* resident child's Agent inbox accepts it directly (waking a `waiting`\n\t* Activation), while an absent one is cold-resumed from its persisted\n\t* Session. The Agent inbox is the only queue, so every accepted message has\n\t* one observable order.\n\t* @param parent - the exact live direct parent authorizing this delivery.\n\t* @param childId - durable child session id.\n\t* @param content - user-role content to deliver.\n\t* @param options - the message source fields and caller cancellation, which stops the\n\t* operation only before inbox acceptance.\n\t* @returns the accepted message's inbox id.\n\t* @throws when continuation services are unavailable, parent authority is\n\t* rejected, or the message was not admitted.\n\t*/\n\tasync followup(parent, childId, content, options) {\n\t\treturn this.requireContinuations().followup(parent, childId, content, options);\n\t}\n\t/**\n\t* Interrupt one live continuable child's current turn under a human parent\n\t* address or an exact live ancestor Agent. Fire-and-return: the cancel\n\t* signal is issued before this returns, but the target may keep running\n\t* until it observes the signal. Unclaimed pending inbox work, the Activation,\n\t* and published descendants are preserved; claimed work is not requeued.\n\t* Once the interrupted driver is idle, a waking send resumes the parked FIFO\n\t* queue. An absent target — including a one-shot or unknown id —\n\t* is an accepted no-op, as is a manager-less composition, which cannot own a\n\t* live Activation.\n\t* @param targetSessionId - the durable child session id to interrupt.\n\t* @param authority - the human parent address or exact live ancestor Agent.\n\t* @throws {SubagentError} `UNAUTHORIZED` when the authority does not own the\n\t* live target.\n\t*/\n\tinterrupt(targetSessionId, authority) {\n\t\tthis.continuations?.interrupt(targetSessionId, authority);\n\t}\n\t/**\n\t* Deliver selected content from one live continuable child to its durable\n\t* direct parent. The child is the authority credential; callers cannot name a\n\t* recipient. Reporting does not conclude the child's turn or Activation.\n\t* @param child - exact live reporting child.\n\t* @param content - selected model-facing content.\n\t* @param options - parent scheduling and pre-acceptance cancellation.\n\t* @returns the stable identity of the parent-accepted message.\n\t* @throws when continuation services are unavailable, sender authorization\n\t* fails, or the direct parent is not live.\n\t*/\n\tasync reportFrom(child, content, options) {\n\t\treturn this.requireContinuations().reportFrom(child, content, options);\n\t}\n\t/**\n\t* Compose one deployment capability into every continuable child's\n\t* unpublished creation context on fresh creation and cold resume. Grants wait\n\t* for the next Activation; removing the contribution revokes every resident\n\t* installation immediately.\n\t* @param contribution - synchronous child-scope installer.\n\t* @returns the exact Cordis effect disposer.\n\t*/\n\tregisterContinuableSetup(contribution) {\n\t\treturn this.ctx.effect(() => this.setupRegistry.register(contribution), \"subagents.registerContinuableSetup()\");\n\t}\n\t/**\n\t* Close continuable admission below exact live parent Agents, stop only their\n\t* visible descendant Activations synchronously, then await admitted scoped\n\t* materializations and release those forests child-first. The scoped cutoff\n\t* lasts until each exact parent leaves the registry; unrelated parent trees\n\t* remain live.\n\t* @param parents - exact host-owned parent Agents entering teardown.\n\t* @returns once every retained descendant Activation released its `AgentHandle`.\n\t* @throws an aggregate error after all branches settle when any failed.\n\t*/\n\tasync drainContinuableDescendants(parents) {\n\t\tconst manager = this.continuations;\n\t\tif (manager === void 0) return;\n\t\tawait manager.drainDescendants(parents);\n\t}\n\t/**\n\t* Enumerate the parent's direct session-backed subagents without loading or\n\t* resuming an Agent and without any query service: the listing merges the live\n\t* session store with optional session persistence (live-preferred) and\n\t* serves each child's durable mode/label from the registered `subagent`\n\t* projection unit down a three-rung ladder — the registry's watermark\n\t* snapshot for a live child; for a cold one, a durable projection-cache\n\t* row when the optional cache serves an own-suffix identity (its `seq`\n\t* gate proves the value postdates the fork seed, where a child's own\n\t* descriptor is immutable once appended), else one persistence inspection\n\t* folded through the registry. The\n\t* projection fold is the single classification authority; per-child\n\t* diagnostics relay a fold that served no identity or a failed inspection,\n\t* never a list-time descriptor parse. Absent persistence, enumeration is\n\t* live-only (a cold child cannot be resumed then either, so its absence is\n\t* capability absence, not an error). This service consults no Agent\n\t* registrations, Activations, or providers.\n\t*\n\t* Every persistence read receives `signal`, and the listing rechecks\n\t* cancellation around each of those awaits. Read rejections that settle\n\t* after an abort become a stable `SubagentError` with code `CANCELLED`.\n\t* @param parentSessionId - parent session whose direct children are listed.\n\t* @param signal - caller-owned cancellation forwarded to persistence reads\n\t* and observed around every read await.\n\t* @returns children and per-child diagnostics ordered by `createdAt`, then id.\n\t* @throws {@link SubagentError} when the projection registry or the session\n\t* store is not mounted, or the caller cancels the listing.\n\t*/\n\tlistChildren(parentSessionId, signal) {\n\t\treturn listChildren(this.ctx, parentSessionId, signal);\n\t}\n\t/**\n\t* Enumerate the root's complete session-backed subagent tree in stable\n\t* pre-order from one live-preferred corpus, without loading or resuming an\n\t* Agent. Ordinary sessions and one-shot children remain traversal nodes so\n\t* continuable descendants below them are discovered; each returned entry\n\t* adds its durable `parentId` and root-relative `depth`. Identity resolution,\n\t* diagnostics, optional persistence, and cancellation follow the same\n\t* projection-backed contract as {@link listChildren}.\n\t* @param rootSessionId - session whose complete descendant tree is listed.\n\t* @param signal - caller-owned cancellation forwarded to persistence reads\n\t* and observed around every read await.\n\t* @returns children and per-candidate diagnostics with tree position, in\n\t* stable pre-order.\n\t* @throws {@link SubagentError} under the same conditions as {@link listChildren}.\n\t*/\n\tlistDescendants(rootSessionId, signal) {\n\t\treturn listDescendants(this.ctx, rootSessionId, signal);\n\t}\n\t/**\n\t* Register a provider under its name. Registration is effect-scoped and HMR\n\t* safe; removing a provider blocks new starts but does not revoke runs that\n\t* were already returned to their holders.\n\t* @param provider - the trusted provider implementation.\n\t* @returns the exact Cordis effect disposer.\n\t*/\n\tregisterProvider(provider) {\n\t\tconst name = provider.name;\n\t\treturn this.ctx.effect(function* () {\n\t\t\tif (this.providers.has(name)) throw new SubagentError(`a subagent provider named \"${name}\" is already registered`, \"DUPLICATE_PROVIDER\");\n\t\t\tthis.providers.set(name, provider);\n\t\t\tyield () => {\n\t\t\t\tthis.providers.delete(name);\n\t\t\t\tthis.emitLifecycle(\"subagent/provider-removed\", name);\n\t\t\t};\n\t\t\tthis.ctx.emit(\"subagent/provider-added\", provider);\n\t\t}.bind(this), \"subagents.registerProvider()\");\n\t}\n\t/**\n\t* Look up a provider by name.\n\t* @param name - the provider name.\n\t* @returns the provider, or undefined when absent.\n\t*/\n\tgetProvider(name) {\n\t\treturn this.providers.get(name);\n\t}\n\t/**\n\t* List registered provider names in insertion order.\n\t* @returns the registered names.\n\t*/\n\tlist() {\n\t\treturn [...this.providers.keys()];\n\t}\n\t/**\n\t* Establish a published child on the named provider. Capability and semantic\n\t* checks run before delegation. Provider ownership lasts until its promise\n\t* fulfills; a rejection therefore has no run for the caller to dispose and\n\t* emits no run lifecycle events. Post-publication turn and infrastructure\n\t* failures settle through the returned run.\n\t* @param name - the provider to use.\n\t* @param request - child label, prompt, parent, signal, and optional capabilities.\n\t* @returns the published holder-owned run.\n\t*/\n\tasync start(name, request) {\n\t\tconst provider = this.expectProvider(name);\n\t\tthis.assertCapabilities(provider, request);\n\t\tassertSubagentMaxDepth(request.maxDepth);\n\t\tif (request.outputSchema !== void 0) assertObjectJsonSchema(request.outputSchema);\n\t\tconst descriptor = snapshotSubagentDescriptor({\n\t\t\tmode: \"one-shot\",\n\t\t\tprovider: name,\n\t\t\t...request.label !== void 0 ? { label: request.label } : {}\n\t\t});\n\t\tconst resolved = {\n\t\t\t...request,\n\t\t\tdescriptor\n\t\t};\n\t\treturn observeRun(this.emitLifecycle, name, request.parent, await provider.start(resolved));\n\t}\n\t/**\n\t* Resolve one provider's detached continuable-creation contribution. Method\n\t* presence on the provider IS the capability, so a provider without it is\n\t* rejected before the manager reserves any child resources.\n\t*/\n\tasync prepareContinuable(name, request) {\n\t\tconst provider = this.expectProvider(name);\n\t\tif (provider.prepareContinuable === void 0) throw new SubagentError(`subagent provider \"${provider.name}\" does not support continuable children (no prepareContinuable capability)`, \"UNSUPPORTED_CAPABILITY\");\n\t\treturn provider.prepareContinuable(request);\n\t}\n\t/** Look up a provider for dispatch or fail loud. */\n\texpectProvider(name) {\n\t\tconst provider = this.providers.get(name);\n\t\tif (provider === void 0) throw new SubagentError(`no subagent provider registered for \"${name}\"`, \"NO_PROVIDER\");\n\t\treturn provider;\n\t}\n\t/** Resolve the optional continuable-subagent manager or fail loud. */\n\trequireContinuations() {\n\t\tif (this.continuations === void 0) throw new SubagentError(\"continuable subagents require the agents service\", \"CONTINUATION_UNAVAILABLE\");\n\t\treturn this.continuations;\n\t}\n\t/**\n\t* Build the lifecycle observer for one continuable Activation's residency\n\t* epoch, so the manager publishes its edges without owning event dispatch.\n\t*/\n\tobserveActivation(provider, childId, parent) {\n\t\treturn createActivationObserver(this.emitLifecycle, provider, childId, parent);\n\t}\n\t/** Reject the first requested capability that the provider lacks. */\n\tassertCapabilities(provider, request) {\n\t\tconst needs = [\n\t\t\t{\n\t\t\t\twhen: request.outputSchema !== void 0,\n\t\t\t\tcap: \"outputSchema\"\n\t\t\t},\n\t\t\t{\n\t\t\t\twhen: request.maxDepth !== void 0,\n\t\t\t\tcap: \"depthLimit\"\n\t\t\t},\n\t\t\t{\n\t\t\t\twhen: request.toolFilter !== void 0,\n\t\t\t\tcap: \"toolFilter\"\n\t\t\t},\n\t\t\t{\n\t\t\t\twhen: request.persona !== void 0,\n\t\t\t\tcap: \"persona\"\n\t\t\t}\n\t\t];\n\t\tfor (const { when, cap } of needs) if (when && !provider.capabilities[cap]) throw new SubagentError(`subagent provider \"${provider.name}\" does not support the \"${cap}\" capability`, \"UNSUPPORTED_CAPABILITY\");\n\t}\n};\n//#endregion\nexport { AssistantOutputFold, NO_START_CAPABILITIES, SUBAGENT_DESCRIPTOR_VERSION, SubagentDepthError, SubagentError, SubagentRunId, SubagentRuntime, SubagentRuntime as default, appendDelegatedPolicyOverrides, applyChildComposition, assertPositiveFinite, assertSubagentMaxDepth, assertUsableCwd, captureDelegatedPolicyOverrides, childSessionMeta, delegationDepthOf, finalAssistantOutput, foldSubagentDescriptor, resolveChildAgentOptions, resolveChildCwd, resolveChildDepth, seedDescriptorTurn, settleRun, settleRunResult, snapshotSubagentDescriptor, subprocessRunHandle, validateConfiguredCwd };\n","import { Service } from \"@deepseek-ai/cordis\";\n//#region lib/types/redact.js\n/**\n* Structural secret redaction for settings values. `role('secret')` fields are\n* removed from a value before it crosses a wire boundary; a sidecar records\n* each schema-declared secret position and whether it currently holds a value,\n* so a configuration surface can render a write-only input without ever\n* receiving the secret itself.\n* @module @deepseek-ai/dsh-settings/redact\n*/\n/** Whether a value is a plain data object the walker may recurse into. */\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction walk(node, value, path, secrets) {\n\tif (node === void 0) return value;\n\tif (node.meta?.role === \"secret\") {\n\t\tsecrets.push({\n\t\t\tpath,\n\t\t\tset: value !== void 0\n\t\t});\n\t\treturn;\n\t}\n\tswitch (node.type) {\n\t\tcase \"object\": {\n\t\t\tconst properties = node.dict ?? {};\n\t\t\tconst source = isRecord(value) ? value : void 0;\n\t\t\tconst rebuilt = {};\n\t\t\tif (source !== void 0) for (const [key, entry] of Object.entries(source)) {\n\t\t\t\tif (key in properties) continue;\n\t\t\t\trebuilt[key] = entry;\n\t\t\t}\n\t\t\tfor (const [key, child] of Object.entries(properties)) {\n\t\t\t\tconst stripped = walk(child, source?.[key], [...path, key], secrets);\n\t\t\t\tif (stripped !== void 0) rebuilt[key] = stripped;\n\t\t\t}\n\t\t\treturn source === void 0 && Object.keys(rebuilt).length === 0 ? value : rebuilt;\n\t\t}\n\t\tcase \"dict\": {\n\t\t\tif (!isRecord(value)) return value;\n\t\t\tconst rebuilt = {};\n\t\t\tfor (const [key, entry] of Object.entries(value)) {\n\t\t\t\tconst stripped = walk(node.inner, entry, [...path, key], secrets);\n\t\t\t\tif (stripped !== void 0) rebuilt[key] = stripped;\n\t\t\t}\n\t\t\treturn rebuilt;\n\t\t}\n\t\tcase \"array\":\n\t\t\tif (!Array.isArray(value)) return value;\n\t\t\treturn value.map((entry, index) => walk(node.inner, entry, [...path, String(index)], secrets));\n\t\tdefault: return value;\n\t}\n}\n/**\n* Remove every `role('secret')` field a schema declares from a value. The\n* walker follows `object`, `dict`, and `array` containers; a secret must be\n* declared directly on a field reachable through those containers (a secret\n* buried inside a union branch or transform is not reachable and must not be\n* modeled that way). The input is never mutated.\n* @param schema - live schemastery schema describing the value.\n* @param value - the value to strip; `undefined` yields an empty record with\n* object-property secret slots still enumerated.\n* @returns the stripped detached value and the ordered secret positions.\n*/\nfunction redactSecrets(schema, value) {\n\tconst secrets = [];\n\treturn {\n\t\tvalue: walk(schema, value, [], secrets),\n\t\tsecrets\n\t};\n}\n//#endregion\n//#region lib/types/index.js\n/**\n* Service Definition for the user-settings capability seam (`ctx.settings`). Providers store one raw document of\n* per-namespace sections; plugins register a namespace schema and read the\n* resolved value, which layers schema defaults, the registrant's composition\n* `base`, and the user document section, in that order.\n* @module @deepseek-ai/dsh-settings\n*/\nconst NAMESPACE_PATTERN = /^[a-z][a-z0-9-]*$/;\n/**\n* Brand a raw string as a {@link SettingsNamespace}.\n* @param value - candidate namespace; lowercase kebab-case, as in plugin short names.\n* @returns the branded namespace.\n*/\nfunction settingsNamespace(value) {\n\tif (!NAMESPACE_PATTERN.test(value)) throw new TypeError(`settings namespace \"${value}\" must match ${String(NAMESPACE_PATTERN)}`);\n\treturn value;\n}\n/**\n* Deep equality over JSON-compatible data (objects, arrays, primitives) — the\n* Service Definition's single change-detection predicate, exported so the invariant\n* companion checks exactly the implementation's relation.\n* @param a - one JSON-compatible value.\n* @param b - the other JSON-compatible value.\n* @returns whether the two values are structurally equal.\n*/\nfunction deepEqualJson(a, b) {\n\tif (a === b) return true;\n\tif (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n\tif (Array.isArray(a) || Array.isArray(b)) {\n\t\tif (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n\t\treturn a.every((entry, index) => deepEqualJson(entry, b[index]));\n\t}\n\tconst left = a;\n\tconst right = b;\n\tconst keys = Object.keys(left);\n\tif (keys.length !== Object.keys(right).length) return false;\n\treturn keys.every((key) => key in right && deepEqualJson(left[key], right[key]));\n}\n/**\n* A write refused because the namespace moved since the caller read it. The\n* Service Definition's serialized write queue orders writes; it cannot tell a fresh writer\n* from one holding a stale snapshot, which is what this reports.\n*/\nvar SettingsConflictError = class extends Error {\n\t/** Stable machine code for wire layers mapping this to their own taxonomy. */\n\tcode = \"SETTINGS_CONFLICT\";\n\t/** The revision the write expected. */\n\texpected;\n\t/** The revision the namespace actually stands at. */\n\tactual;\n\t/**\n\t* @param ns - the namespace whose write was refused.\n\t* @param expected - the revision the caller sent.\n\t* @param actual - the revision now stored.\n\t*/\n\tconstructor(ns, expected, actual) {\n\t\tsuper(`settings namespace \"${ns}\" changed since it was read (expected revision ${String(expected)}, now ${String(actual)})`);\n\t\tthis.name = \"SettingsConflictError\";\n\t\tthis.expected = expected;\n\t\tthis.actual = actual;\n\t}\n};\n/** Whether a value is a plain data object (not an array, null, or class instance). */\nfunction isPlainObject(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\tconst proto = Object.getPrototypeOf(value);\n\treturn proto === Object.prototype || proto === null;\n}\n/** Apply one path op to a detached section, returning the next section. */\nfunction applyPathOp(section, op) {\n\tconst [head, ...rest] = op.path;\n\tif (head === void 0) {\n\t\tif (op.op === \"unset\") return {};\n\t\tif (!isPlainObject(op.value)) throw new TypeError(\"settings mutate: setting the section root requires a plain object\");\n\t\treturn { ...op.value };\n\t}\n\tif (rest.length === 0) {\n\t\tif (op.op === \"set\") return {\n\t\t\t...section,\n\t\t\t[head]: op.value\n\t\t};\n\t\tconst { [head]: _removed, ...kept } = section;\n\t\treturn kept;\n\t}\n\tconst child = section[head];\n\tif (!isPlainObject(child)) {\n\t\tif (op.op === \"unset\") return section;\n\t\treturn {\n\t\t\t...section,\n\t\t\t[head]: applyPathOp({}, {\n\t\t\t\t...op,\n\t\t\t\tpath: rest\n\t\t\t})\n\t\t};\n\t}\n\treturn {\n\t\t...section,\n\t\t[head]: applyPathOp(child, {\n\t\t\t...op,\n\t\t\tpath: rest\n\t\t})\n\t};\n}\n/** Human label for a value that lossless JSON cannot represent (numbers reject inline). */\nfunction describeRejected(value) {\n\tif (value === void 0) return \"undefined\";\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst name = Object.getPrototypeOf(value)?.constructor?.name;\n\t\treturn name === void 0 || name === \"Object\" ? \"a non-plain object\" : `a ${name}`;\n\t}\n\treturn `a ${typeof value}`;\n}\n/**\n* Detach and validate one write input in a single walk before persistence:\n* only JSON data (plain objects, arrays, strings, finite numbers,\n* booleans, `null`) may reach a provider document. `structuredClone` alone\n* would admit Dates, Maps, BigInts, and cycles that YAML/JSON storage then\n* silently distorts on the reload round-trip. `undefined` entries in objects\n* are skipped — the same sparse-patch semantics as {@link mergeLayers} — while\n* an `undefined` array entry is rejected rather than coerced.\n* @param root - plain-object write input (caller-checked).\n* @param reject - builds the validation error from a value label and its `$`-rooted path.\n* @returns the detached JSON-compatible clone.\n*/\nfunction cloneJsonShaped(root, reject) {\n\tconst visiting = /* @__PURE__ */ new WeakSet();\n\tconst clone = (value, path) => {\n\t\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n\t\tif (typeof value === \"number\") {\n\t\t\tif (!Number.isFinite(value)) throw reject(\"a non-finite number\", path);\n\t\t\treturn value;\n\t\t}\n\t\tif (Array.isArray(value)) {\n\t\t\tif (visiting.has(value)) throw reject(\"a circular reference\", path);\n\t\t\tvisiting.add(value);\n\t\t\tconst entries = value.map((entry, index) => clone(entry, `${path}[${index}]`));\n\t\t\tvisiting.delete(value);\n\t\t\treturn entries;\n\t\t}\n\t\tif (isPlainObject(value)) {\n\t\t\tif (visiting.has(value)) throw reject(\"a circular reference\", path);\n\t\t\tvisiting.add(value);\n\t\t\tconst out = {};\n\t\t\tfor (const [key, entry] of Object.entries(value)) {\n\t\t\t\tif (entry === void 0) continue;\n\t\t\t\tout[key] = clone(entry, `${path}.${key}`);\n\t\t\t}\n\t\t\tvisiting.delete(value);\n\t\t\treturn out;\n\t\t}\n\t\tthrow reject(describeRejected(value), path);\n\t};\n\treturn clone(root, \"$\");\n}\n/**\n* Layer `over` onto `under`: plain objects merge recursively, every other\n* value (arrays included) replaces the lower layer wholesale. `over` never\n* carries `undefined` entries — sections come from parsed documents and write\n* snapshots pass {@link cloneJsonShaped}, which strips them so a sparse patch\n* cannot erase lower keys.\n*/\nfunction mergeLayers(under, over) {\n\tif (over === void 0) return under;\n\tif (!isPlainObject(under) || !isPlainObject(over)) return over;\n\tconst merged = { ...under };\n\tfor (const [key, value] of Object.entries(over)) merged[key] = key in merged ? mergeLayers(merged[key], value) : value;\n\treturn merged;\n}\n/** Recursively freeze one resolved value so handed-out snapshots stay immutable. */\nfunction deepFreeze(value) {\n\tif (typeof value !== \"object\" || value === null || Object.isFrozen(value)) return value;\n\tfor (const entry of Object.values(value)) deepFreeze(entry);\n\treturn Object.freeze(value);\n}\n/**\n* Abstract settings service. Providers implement raw-document storage\n* (`load`/`persist`) and push external changes through {@link Settings.publish};\n* the base class owns namespace registration, resolution, validation, change\n* detection, and the `settings/updated` commit event.\n*/\nvar SettingsProvider = class extends Service {\n\tregistrations = /* @__PURE__ */ new Map();\n\t/** Latest published raw document; empty until the provider's first publish. */\n\tdocument = {};\n\t/** Per-namespace write chains; settled tails, so a failure never poisons the queue. */\n\twriteQueues = /* @__PURE__ */ new Map();\n\t/** In-flight watcher invocation segments, drained by the dispose teardown. */\n\tpendingTails = /* @__PURE__ */ new Set();\n\t/** Set at service dispose: refuse new writes while queued ones drain. */\n\tstopped = false;\n\t/** Opaque read of {@link stopped}: control flow cannot narrow it across awaits. */\n\tisStopped() {\n\t\treturn this.stopped;\n\t}\n\tconstructor(ctx) {\n\t\tsuper(ctx, \"settings\");\n\t}\n\t/**\n\t* Load the provider's document once and publish it before the service\n\t* becomes injectable, and register the write-drain teardown. Providers with\n\t* their own init (watchers, connections) delegate here first via\n\t* `yield* super[Service.init]()`; their disposers then run before the drain.\n\t*/\n\tasync *[Service.init]() {\n\t\tyield async () => {\n\t\t\tthis.stopped = true;\n\t\t\tawait Promise.allSettled([...this.writeQueues.values(), ...this.pendingTails]);\n\t\t};\n\t\tthis.publish(await this.load());\n\t}\n\t/**\n\t* Absolute path of the provider's user-editable document, when its storage\n\t* is one local file. Configuration surfaces use this only as availability\n\t* metadata; the guarded open operation resolves the path again Host-side.\n\t* Non-file providers leave it undefined and expose no open-document affordance.\n\t* @returns the absolute local document path, or undefined for non-file storage.\n\t*/\n\tget documentPath() {}\n\t/**\n\t* Prepare the provider's user-editable document for a native editor. File\n\t* providers may materialize an absent document before returning its path;\n\t* non-file providers return undefined.\n\t* @returns the absolute local document path, or undefined for non-file storage.\n\t*/\n\tprepareDocument() {\n\t\treturn Promise.resolve(this.documentPath);\n\t}\n\t/**\n\t* Register a namespace schema and receive its owner scope. The registration\n\t* is an effect on the calling plugin's fiber: disposing that fiber removes\n\t* the namespace and its observers. An invalid stored section fails the\n\t* registration itself — the earliest point where the schema can judge it.\n\t* @param ns - unique namespace; duplicate registration fails loud.\n\t* @param schema - schemastery schema resolving this namespace's value.\n\t* @param options - composition `base` layer and effect timing.\n\t* @returns the owner scope for reads, observation, and updates.\n\t*/\n\tregister(ns, schema, options) {\n\t\tif (this.registrations.has(ns)) throw new Error(`settings namespace \"${ns}\" is already registered`);\n\t\tconst registration = {\n\t\t\tns,\n\t\t\tschema,\n\t\t\tbase: options?.base,\n\t\t\tapplies: options?.applies ?? \"live\",\n\t\t\t...options?.validate === void 0 ? {} : { validate: options.validate },\n\t\t\tresolved: deepFreeze(this.resolve(schema, options?.base, this.section(ns), options?.validate)),\n\t\t\trevision: 0,\n\t\t\twatchers: /* @__PURE__ */ new Set()\n\t\t};\n\t\tthis.ctx.effect(() => {\n\t\t\tthis.registrations.set(ns, registration);\n\t\t\treturn () => this.registrations.delete(ns);\n\t\t}, `settings.register(${JSON.stringify(String(ns))})`);\n\t\treturn {\n\t\t\tget: () => registration.resolved,\n\t\t\twatch: (callback) => {\n\t\t\t\tconst watcher = {\n\t\t\t\t\tcallback,\n\t\t\t\t\ttail: Promise.resolve(),\n\t\t\t\t\tactive: true\n\t\t\t\t};\n\t\t\t\tregistration.watchers.add(watcher);\n\t\t\t\treturn () => {\n\t\t\t\t\twatcher.active = false;\n\t\t\t\t\tregistration.watchers.delete(watcher);\n\t\t\t\t};\n\t\t\t},\n\t\t\tupdate: (patch) => this.update(ns, patch),\n\t\t\treplace: (section) => this.replace(ns, section)\n\t\t};\n\t}\n\t/**\n\t* Describe every registered namespace for configuration surfaces, including\n\t* the composition `base` and raw user layers so a form can mark which fields\n\t* the user overrode (presence in `user`) and what a reset returns to.\n\t* @param options - redaction switch; wire surfaces must redact.\n\t* @returns one descriptor per registered namespace, in registration order.\n\t*/\n\tdescribe(options) {\n\t\treturn [...this.registrations.values()].map((registration) => {\n\t\t\tlet user;\n\t\t\ttry {\n\t\t\t\tuser = this.section(registration.ns);\n\t\t\t} catch {\n\t\t\t\tuser = void 0;\n\t\t\t}\n\t\t\tconst base = registration.base === void 0 ? void 0 : structuredClone(registration.base);\n\t\t\tconst detachedUser = user === void 0 ? void 0 : structuredClone(user);\n\t\t\tconst descriptor = {\n\t\t\t\tns: registration.ns,\n\t\t\t\tschema: registration.schema.toJSON(),\n\t\t\t\tvalue: registration.resolved,\n\t\t\t\trevision: registration.revision,\n\t\t\t\t...base === void 0 ? {} : { base },\n\t\t\t\t...detachedUser === void 0 ? {} : { user: detachedUser },\n\t\t\t\tapplies: registration.applies\n\t\t\t};\n\t\t\tif (options?.redactSecrets !== true) return descriptor;\n\t\t\tconst schema = registration.schema;\n\t\t\tconst redacted = redactSecrets(schema, registration.resolved);\n\t\t\treturn {\n\t\t\t\t...descriptor,\n\t\t\t\tvalue: redacted.value,\n\t\t\t\t...base === void 0 ? {} : { base: redactSecrets(schema, base).value },\n\t\t\t\t...detachedUser === void 0 ? {} : { user: redactSecrets(schema, detachedUser).value },\n\t\t\t\tsecrets: redacted.secrets\n\t\t\t};\n\t\t});\n\t}\n\t/**\n\t* Read one registered namespace's resolved value.\n\t* @param ns - the namespace to read.\n\t* @returns the resolved value, or `undefined` while unregistered.\n\t*/\n\tget(ns) {\n\t\treturn this.registrations.get(ns)?.resolved;\n\t}\n\t/**\n\t* Merge a patch into one registered namespace's user layer, validate the\n\t* resolved candidate, persist through the provider, then commit and emit.\n\t* A validation failure rejects before anything is persisted. Writes to one\n\t* namespace are serialized: concurrent updates apply in call order, each\n\t* merging over the previous write's committed section.\n\t* @param ns - the registered namespace to update.\n\t* @param patch - plain-object patch over the user section.\n\t* @param expectedRevision - the descriptor `revision` the caller read; a\n\t* namespace that moved past it rejects with {@link SettingsConflictError}.\n\t*/\n\tasync update(ns, patch, expectedRevision) {\n\t\treturn this.write(ns, patch, \"merge\", expectedRevision);\n\t}\n\t/**\n\t* Replace one registered namespace's user section wholesale, validate,\n\t* persist, then commit and emit. Keys absent from `section` fall back to the\n\t* composition `base` and schema defaults — this is the removal/reset path a\n\t* merge-only patch cannot express (`replace({})` re-inherits everything).\n\t* @param ns - the registered namespace to replace.\n\t* @param section - the complete next user section.\n\t* @param expectedRevision - the descriptor `revision` the caller read; a\n\t* namespace that moved past it rejects with {@link SettingsConflictError}.\n\t*/\n\tasync replace(ns, section, expectedRevision) {\n\t\treturn this.write(ns, section, \"replace\", expectedRevision);\n\t}\n\t/**\n\t* Apply path-addressed edits to one registered namespace's user section,\n\t* validate, persist, then commit and emit. The ops are applied to the\n\t* section as it stands when the write reaches the front of the queue, so a\n\t* caller never has to restate fields it did not touch — and, crucially,\n\t* cannot delete fields it never saw. This is the write path for any caller\n\t* holding a redacted view; `replace` remains the wholesale reset.\n\t* @param ns - the registered namespace to edit.\n\t* @param ops - ordered path edits; later ops observe earlier ones.\n\t* @param expectedRevision - the descriptor `revision` the caller read; a\n\t* namespace that moved past it rejects with {@link SettingsConflictError}.\n\t*/\n\tasync mutate(ns, ops, expectedRevision) {\n\t\tif (!Array.isArray(ops)) throw new TypeError(`settings mutate for \"${ns}\" must be an array of path ops`);\n\t\tfor (const op of ops) {\n\t\t\tif (!isPlainObject(op) || op[\"op\"] !== \"set\" && op[\"op\"] !== \"unset\") throw new TypeError(`settings mutate for \"${ns}\" ops must be {op:'set'|'unset', path}`);\n\t\t\tif (!Array.isArray(op[\"path\"]) || op[\"path\"].some((part) => typeof part !== \"string\")) throw new TypeError(`settings mutate for \"${ns}\" op paths must be arrays of strings`);\n\t\t}\n\t\treturn this.write(ns, ops, \"mutate\", expectedRevision);\n\t}\n\t/** Validate a write, then queue it on the namespace's serialized write chain. */\n\twrite(ns, input, mode, expectedRevision) {\n\t\tconst verb = mode === \"merge\" ? \"update\" : mode === \"replace\" ? \"replace\" : \"mutate\";\n\t\tconst registration = this.registrations.get(ns);\n\t\tif (registration === void 0) throw new Error(`settings namespace \"${ns}\" is not registered`);\n\t\tif (this.isStopped()) throw new Error(`settings service is disposed: \"${ns}\" cannot be written`);\n\t\tif (!this.writable) throw new Error(`settings provider is read-only: \"${ns}\" cannot be updated in-process`);\n\t\tlet payload;\n\t\tif (mode === \"mutate\") payload = { ops: input };\n\t\telse {\n\t\t\tif (!isPlainObject(input)) throw new TypeError(`settings ${verb} for \"${ns}\" must be a plain object`);\n\t\t\tpayload = input;\n\t\t}\n\t\tconst snapshot = cloneJsonShaped(payload, (label, path) => /* @__PURE__ */ new TypeError(`settings ${verb} for \"${ns}\" must contain only JSON-compatible data (found ${label} at ${path})`));\n\t\tconst run = (this.writeQueues.get(ns) ?? Promise.resolve()).catch(() => void 0).then(async () => {\n\t\t\tif (this.isStopped()) throw new Error(`settings service was disposed before the queued \"${ns}\" ${verb} ran`);\n\t\t\tif (this.registrations.get(ns) !== registration) throw new Error(`settings namespace \"${ns}\" registration was disposed before the queued ${verb} ran`);\n\t\t\tconst current = this.section(ns) ?? {};\n\t\t\tif (expectedRevision !== void 0 && expectedRevision !== registration.revision) throw new SettingsConflictError(ns, expectedRevision, registration.revision);\n\t\t\tconst section = mode === \"merge\" ? mergeLayers(current, snapshot) : mode === \"replace\" ? snapshot : snapshot[\"ops\"].reduce(applyPathOp, current);\n\t\t\tconst next = deepFreeze(this.resolve(registration.schema, registration.base, section, registration.validate));\n\t\t\tawait this.persist(ns, section);\n\t\t\tthis.document[ns] = section;\n\t\t\tif (this.registrations.get(ns) === registration && !this.isStopped()) {\n\t\t\t\tthis.bumpRevision(registration, current, section);\n\t\t\t\tthis.commit(registration, next, \"update\");\n\t\t\t}\n\t\t});\n\t\tthis.writeQueues.set(ns, run);\n\t\treturn run;\n\t}\n\t/**\n\t* Provider hook: commit a complete raw document observed in storage. Each\n\t* registered namespace re-resolves; an invalid section keeps that\n\t* namespace's last good value and warns, other namespaces still commit.\n\t* @param doc - the detached raw document (unregistered sections preserved).\n\t* @param source - change origin; defaults to `provider`.\n\t*/\n\tpublish(doc, source = \"provider\") {\n\t\tconst before = /* @__PURE__ */ new Map();\n\t\tfor (const registration of this.registrations.values()) try {\n\t\t\tbefore.set(registration.ns, this.section(registration.ns));\n\t\t} catch {\n\t\t\tbefore.set(registration.ns, void 0);\n\t\t}\n\t\tthis.document = doc;\n\t\tfor (const registration of this.registrations.values()) {\n\t\t\tlet next;\n\t\t\ttry {\n\t\t\t\tnext = deepFreeze(this.resolve(registration.schema, registration.base, this.section(registration.ns), registration.validate));\n\t\t\t} catch (error) {\n\t\t\t\tthis.ctx.logger.warn(\"settings: keeping last good \\\"%s\\\" after invalid stored section\", registration.ns);\n\t\t\t\tthis.ctx.logger.warn(error);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.bumpRevision(registration, before.get(registration.ns), this.section(registration.ns));\n\t\t\tthis.commit(registration, next, source);\n\t\t}\n\t}\n\t/** Read one namespace's raw user section, rejecting non-object sections. */\n\tsection(ns) {\n\t\tconst section = this.document[ns];\n\t\tif (section === void 0) return void 0;\n\t\tif (!isPlainObject(section)) throw new TypeError(`settings section \"${ns}\" must be an object of keys`);\n\t\treturn section;\n\t}\n\t/** Resolve one namespace value: schema defaults, then `base`, then the user layer. */\n\tresolve(schema, base, section, validate) {\n\t\tconst value = schema(mergeLayers(base, section));\n\t\tvalidate?.(value);\n\t\treturn value;\n\t}\n\t/**\n\t* Advance a namespace's revision when its RAW section changed, and announce\n\t* it. Deliberately independent of {@link commit}'s resolved-value equality:\n\t* storing an override equal to the composition base leaves the resolved\n\t* value alone but changes what the document says, which is exactly what a\n\t* configuration surface must re-read.\n\t*/\n\tbumpRevision(registration, before, after) {\n\t\tif (deepEqualJson(before, after)) return;\n\t\tregistration.revision += 1;\n\t\tthis.emitDocumentUpdated(registration.ns, registration.revision);\n\t}\n\t/** Contained fan-out of `settings/document-updated`, mirroring {@link commit}'s. */\n\temitDocumentUpdated(ns, revision) {\n\t\tlet invariantFailure;\n\t\tconst args = [\n\t\t\t\"settings/document-updated\",\n\t\t\tns,\n\t\t\trevision\n\t\t];\n\t\tfor (const listener of this.ctx.events.dispatch(\"emit\", args)) try {\n\t\t\tconst returned = listener(ns, revision);\n\t\t\tif (returned != null && typeof returned.then === \"function\") Promise.resolve(returned).then(void 0, (error) => {\n\t\t\t\tthis.warnListenerFailure(ns, error);\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error?.code === \"INVARIANT\") {\n\t\t\t\tinvariantFailure ??= error;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.warnListenerFailure(ns, error);\n\t\t}\n\t\tif (invariantFailure !== void 0) throw invariantFailure;\n\t}\n\t/** Commit a resolved value when changed: swap, notify watchers, emit the event. */\n\tcommit(registration, next, source) {\n\t\tconst prev = registration.resolved;\n\t\tif (deepEqualJson(next, prev)) return;\n\t\tregistration.resolved = next;\n\t\tfor (const watcher of [...registration.watchers]) {\n\t\t\tconst segment = watcher.tail.then(() => {\n\t\t\t\tif (!watcher.active || this.isStopped()) return;\n\t\t\t\treturn watcher.callback(next, prev);\n\t\t\t}).then(() => void 0, (error) => {\n\t\t\t\tthis.warnWatcherFailure(registration.ns, error);\n\t\t\t});\n\t\t\twatcher.tail = segment;\n\t\t\tthis.pendingTails.add(segment);\n\t\t\tsegment.then(() => this.pendingTails.delete(segment));\n\t\t}\n\t\tlet invariantFailure;\n\t\tconst args = [\n\t\t\t\"settings/updated\",\n\t\t\tregistration.ns,\n\t\t\tnext,\n\t\t\tprev,\n\t\t\tsource\n\t\t];\n\t\tfor (const listener of this.ctx.events.dispatch(\"emit\", args)) try {\n\t\t\tconst returned = listener(registration.ns, next, prev, source);\n\t\t\tif (returned != null && typeof returned.then === \"function\") Promise.resolve(returned).then(void 0, (error) => {\n\t\t\t\tthis.warnListenerFailure(registration.ns, error);\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error?.code === \"INVARIANT\") {\n\t\t\t\tinvariantFailure ??= error;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.warnListenerFailure(registration.ns, error);\n\t\t}\n\t\tif (invariantFailure !== void 0) throw invariantFailure;\n\t}\n\t/** Contained-watcher diagnostic shared by the sync and async failure paths. */\n\twarnWatcherFailure(ns, error) {\n\t\tthis.ctx.logger.warn(\"settings: watcher for \\\"%s\\\" failed\", ns);\n\t\tthis.ctx.logger.warn(error);\n\t}\n\t/** Contained-listener diagnostic shared by the sync and async failure paths. */\n\twarnListenerFailure(ns, error) {\n\t\tthis.ctx.logger.warn(\"settings: a settings/updated listener for \\\"%s\\\" failed\", ns);\n\t\tthis.ctx.logger.warn(error);\n\t}\n};\n/**\n* Value mirror of the `FiberState` members {@link isUnloading} compares\n* against: a const enum has no runtime object to import, and the value is\n* needed at runtime (same rationale as the CLI boot driver's mirror).\n*/\nconst FIBER_DISPOSED = 4;\nconst FIBER_UNLOADING = 5;\n/** Whether the consumer's own fiber is tearing down (not just losing the settings service). */\nfunction isUnloading(ctx) {\n\tconst state = ctx.fiber.state;\n\treturn state === FIBER_UNLOADING || state === FIBER_DISPOSED;\n}\n/**\n* Install the canonical optional-settings consumer wiring: while a settings\n* service exists, register `ns` with the consumer's composition entry as the\n* `base` layer and point the source thunk at the resolved scope; when the\n* service goes away (disposal, provider reload), fall back to the entry so\n* the consumer keeps working exactly as composed. The registration rides the\n* scoped fiber, so no settings service ever mounted means none of this runs.\n* @param ctx - consumer plugin context owning the wiring.\n* @param ns - the consumer-owned settings namespace.\n* @param schema - schema resolving the namespace (typically the plugin Config).\n* @param entry - the consumer's composition entry config, used as `base`.\n* @param hooks - source sink and change notification.\n*/\nfunction installSettingsSection(ctx, ns, schema, entry, hooks) {\n\tctx.inject([\"settings\"], (sctx) => {\n\t\tconst scope = sctx.settings.register(ns, schema, {\n\t\t\tbase: entry,\n\t\t\t...hooks.validate === void 0 ? {} : { validate: hooks.validate }\n\t\t});\n\t\thooks.setSource(() => scope.get());\n\t\tsctx.effect(() => () => {\n\t\t\tif (isUnloading(ctx)) return;\n\t\t\thooks.setSource(() => entry);\n\t\t\thooks.onChange();\n\t\t});\n\t\thooks.onChange();\n\t\tscope.watch(() => {\n\t\t\tif (isUnloading(ctx)) return;\n\t\t\thooks.onChange();\n\t\t});\n\t});\n}\n//#endregion\nexport { SettingsConflictError, SettingsProvider, SettingsProvider as default, deepEqualJson, installSettingsSection, redactSecrets, settingsNamespace };\n","/**\n * dsh-subagent-library: a settings-driven named-subagent library.\n *\n * Entries live in the `subagent-library.entries` settings document (hot\n * reloaded, no restart), keyed by id. Each entry names a role: a model, an\n * optional persona, an optional tool filter, a depth cap and a background\n * mode. The plugin registers two model-facing tools on the HOST plane so every\n * session sees them regardless of agent preset:\n *\n * - `list_subagents` — the catalog (id + description + model), so the model\n * can pick an entry instead of guessing that a role exists.\n * - `delegate` — start one library subagent by `library_id` (foreground,\n * background one-shot task, or continuable child per the entry).\n *\n * Plus a `/subagent` slash command listing the catalog for humans.\n *\n * Delegation itself goes through the standard `ctx.subagents` seam with the\n * spawn provider (or any provider an entry names), so children keep the\n * harness' ordinary subagent semantics: approval pinned to `never` on\n * delegation, inherited sandbox scope, depth caps, and continuable support\n * where the provider offers it.\n *\n * @module dsh-subagent-library\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport z from '@deepseek-ai/schemastery'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { defineTool } from '@deepseek-ai/dsh-tools'\nimport type { ContentBlock } from '@deepseek-ai/dsh-llm'\nimport type { JsonValue } from '@deepseek-ai/dsh-session'\nimport { assertSubagentMaxDepth, settleRun } from '@deepseek-ai/dsh-subagent'\nimport type { SubagentResult, SubagentRun, SubagentStartRequest } from '@deepseek-ai/dsh-subagent'\nimport { settingsNamespace } from '@deepseek-ai/dsh-settings'\nimport type { SettingsNamespace, SettingsProvider } from '@deepseek-ai/dsh-settings'\nimport type { CommandResult } from '@deepseek-ai/dsh-commands'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\n\nexport const name = 'subagent-library'\nexport const inject = ['subagents', 'tools', 'systemPrompt']\n\nconst ENTRY_ID = /^[a-z0-9][a-z0-9-]*$/\nconst LIBRARY_SECTION_ORDER = 116.6\n/** Recursion cap applied when an entry omits maxDepth and the transport can\n * enforce it — the harness itself imposes no global delegation cap\n * (resolveChildDepth checks only an explicit value), and the official\n * subagent tool defaults to 3 to keep chained delegation bounded. */\nconst DEFAULT_MAX_DEPTH = 3\n\n/** Optional child tool scoping: named tools vanish from the child's prompt AND refuse execution. */\nexport interface ToolFilter {\n /** Global tool names the child keeps; everything else is removed. */\n allow?: string[]\n /** Global tool names removed from the child. */\n deny?: string[]\n}\n\n/** One named library entry. */\nexport interface Entry {\n /** Role description surfaced to the model in `list_subagents`; keep it self-contained. */\n description: string\n /** LLM provider route for the child (e.g. `deepseek-official`, `kimi-coding`); omitted children use the caller's loop defaults. */\n provider?: string\n /** Provider model id; omitted children use the caller's loop defaults. */\n model?: string\n /** Subagent transport provider (e.g. `spawn`); defaults to the plugin-level `subagentProvider`. */\n subagentProvider?: string\n /** Per-request output cap for the child. */\n maxTokens?: number\n /** Per-child persona shadowing the deployment persona for this child. */\n persona?: string\n /** Child tool scoping. */\n toolFilter?: ToolFilter\n /** Absolute delegation-depth cap for the child; requires provider depthLimit. */\n maxDepth?: number\n /** `one-shot` (default) or `continuable` (durable, resumable background child). */\n backgroundMode?: 'one-shot' | 'continuable'\n}\n\nexport interface Config {\n /** Subagent transport provider used when an entry names none. */\n subagentProvider: string\n /** Named subagent library, keyed by id (`[a-z0-9][a-z0-9-]*`). */\n entries: Record<string, Entry>\n}\n\nconst EntrySchema = z.object({\n description: z.string().required(),\n provider: z.string(),\n model: z.string(),\n subagentProvider: z.string(),\n maxTokens: z.natural().max(Number.MAX_SAFE_INTEGER),\n persona: z.string(),\n toolFilter: z.object({\n allow: z.array(z.string()).default(undefined as unknown as string[]),\n deny: z.array(z.string()).default(undefined as unknown as string[]),\n }).default(undefined as unknown as { allow: string[]; deny: string[] }),\n maxDepth: z.natural().max(Number.MAX_SAFE_INTEGER),\n backgroundMode: z.union(['one-shot', 'continuable'] as const).default('one-shot'),\n})\n\nexport const Config: z<Config> = z.object({\n subagentProvider: z.string().default('spawn'),\n entries: z.dict(EntrySchema).default({}),\n})\n\n/** Render text blocks from the canonical JSON block array without trusting arbitrary values. */\nfunction outputValueText(values: readonly JsonValue[]): string {\n return values\n .filter((value): value is { type: 'text'; text: string } =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n && value.type === 'text' && typeof value.text === 'string')\n .map(value => value.text)\n .join('')\n}\n\n/** Settle pending startup without rejecting the task producer contract. */\nasync function settleStart(start: Promise<SubagentRun>, signal: AbortSignal): Promise<{ status: string; detail?: string }> {\n try {\n return await settleRun(await start)\n } catch (error: unknown) {\n return signal.aborted\n ? { status: 'killed' }\n : { status: 'failed', detail: String(error) }\n }\n}\n\n/** Foreground collection: await the child, dispose the run, map stop reasons.\n * `run.result` rejection must still release the run (mirrors settleRun). */\nasync function settleForegroundRun(run: SubagentRun): Promise<{ kind: 'foreground'; runId: string; output: JsonValue[] }> {\n let result: SubagentResult\n try {\n result = await run.result\n } finally {\n await run.dispose().catch(() => { /* keep the original failure */ })\n }\n if (result.stopReason !== 'completed') {\n const text = outputValueText(result.output as unknown as JsonValue[])\n throw new Error(`subagent run ended: ${result.stopReason}${text ? ` — partial output: ${text}` : ''}`)\n }\n return { kind: 'foreground', runId: run.id, output: result.output as unknown as JsonValue[] }\n}\n\n/** Minimal structural view of the optional jobs service (dsh-jobs + dsh-tool-jobs). */\ninterface JobRunner {\n start(options: {\n kind: string\n label: string\n owner: unknown\n run: () => { cancel: (reason?: string) => void; done: Promise<unknown> }\n }): string\n}\n\n/** Canonical delegate tool result (JsonValue-compatible, no explicit-undefined properties). */\ntype DelegateResult = {\n kind: string\n runId?: string\n output?: JsonValue[]\n jobId?: string\n subagentId?: string\n}\n\nexport function apply(ctx: Context, config: Config) {\n // ── settings seam: entry config as base, user document hot-reloaded ───────\n // Inline the optional-settings wiring (same pattern as dsh-agent-presets):\n // `installSettingsSection` is deliberately NOT used — in this harness build\n // its registration is dropped for bundle-loaded plugins. The inject callback\n // fires once the settings service finishes initializing.\n let source: (() => Config) | undefined\n let settingsService: SettingsProvider | undefined\n let settingsNs: SettingsNamespace | undefined\n /** Non-null when the settings seam could not register this namespace (e.g. a\n * hand-edited settings.yaml section fails the Config schema). Registration\n * failing inside a Cordis child fiber would otherwise leave the library\n * silently empty; surface the cause through every consumer instead. */\n let settingsFailure: string | undefined\n ctx.inject(['settings'], (sctx: Context) => {\n settingsService = sctx.settings\n settingsNs = settingsNamespace('subagent-library')\n try {\n const scope = sctx.settings.register(settingsNs, Config, { base: config })\n source = () => scope.get()\n sctx.effect(() => () => {\n source = () => config\n })\n scope.watch(() => {\n // nothing derived is memoized — every operation re-reads the source.\n })\n } catch (error) {\n settingsFailure = `subagent-library 设置段注册失败:${String(error)}。请检查 $DSH_HOME/settings.yaml 的 subagent-library 段(常见:description 缺失、entries 写成数组、YAML 布尔/字符串误写)。`\n }\n })\n /** Library entries restricted to schema-consistent ids: a hand-written key\n * like `k3_reviewer` passes z.dict (any string key) but can never be\n * delegated or deleted, so it is filtered out of every view. Saving any\n * entry then replaces the document and drops the orphaned key. */\n const filterEntries = (raw: Record<string, Entry>): Record<string, Entry> =>\n Object.fromEntries(Object.entries(raw).filter(([id]) => ENTRY_ID.test(id)))\n const resolveConfig = (): Config => {\n const base = source !== undefined ? source() : config\n return { ...base, entries: filterEntries(base.entries) }\n }\n\n // ── settings page API (own HTTP routes) ────────────────────────────────────\n // The Web gateway only exposes namespaces on its own allowlist\n // (`WEB_SETTINGS_NAMESPACES` / model-provider namespaces in\n // @deepseek-ai/dsh-host-apiproxy), so a third-party plugin's settings\n // section is invisible to the browser through `api.settings.*`. Serve the\n // editor through the plugin's own routes instead, exactly like fish-tts.\n const MAX_BODY_BYTES = 1 << 20\n\n /** Distinguish \"over the size cap\" (413) from \"not valid JSON\" (400). */\n type BodyRead =\n | { ok: true; body: Record<string, unknown> }\n | { ok: false; error: 'too-large' | 'bad-json' }\n\n const readJsonBody = async (req: IncomingMessage): Promise<BodyRead> => {\n const chunks: Buffer[] = []\n let size = 0\n for await (const chunk of req) {\n const buffer = chunk as Buffer\n size += buffer.length\n if (size > MAX_BODY_BYTES) return { ok: false, error: 'too-large' }\n chunks.push(buffer)\n }\n if (chunks.length === 0) return { ok: true, body: {} }\n try {\n const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'))\n return typeof parsed === 'object' && parsed !== null\n ? { ok: true, body: parsed as Record<string, unknown> }\n : { ok: false, error: 'bad-json' }\n } catch {\n return { ok: false, error: 'bad-json' }\n }\n }\n\n const sendJson = (res: ServerResponse, status: number, value: unknown): void => {\n const body = JSON.stringify(value)\n res.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'content-length': Buffer.byteLength(body),\n 'cache-control': 'no-store',\n })\n res.end(body)\n }\n\n // Cross-origin write protection (same posture as dsh-plugin-fish-tts).\n const guardWrite = (req: IncomingMessage, res: ServerResponse): boolean => {\n const contentType = (req.headers['content-type'] ?? '').split(';')[0]?.trim().toLowerCase()\n if (contentType !== 'application/json') {\n sendJson(res, 415, { ok: false, error: 'content-type-json-required' })\n return false\n }\n const origin = req.headers.origin\n if (origin !== undefined) {\n let originHost = ''\n try {\n originHost = new URL(origin).host\n } catch {\n originHost = ''\n }\n const hostHeader = req.headers.host ?? ''\n const sameOrigin = originHost !== '' && originHost === hostHeader\n const loopback = originHost.startsWith('127.0.0.1:')\n || originHost.startsWith('localhost:')\n || originHost.startsWith('[::1]:')\n if (!sameOrigin && !loopback) {\n sendJson(res, 403, { ok: false, error: 'cross-origin-forbidden' })\n return false\n }\n }\n return true\n }\n\n /** Raw `entries` map from one descriptor layer; arrays and non-objects are\n * rejected so a damaged document cannot masquerade as the library. */\n const entriesOf = (section: unknown): Record<string, Entry> | undefined => {\n if (typeof section !== 'object' || section === null || Array.isArray(section)) return undefined\n const entries = (section as { entries?: unknown }).entries\n return typeof entries === 'object' && entries !== null && !Array.isArray(entries)\n ? entries as Record<string, Entry>\n : undefined\n }\n\n const currentView = (): { writable: boolean; revision: number; entries: Record<string, Entry> } | null => {\n const svc = settingsService\n const ns = settingsNs\n if (svc === undefined || ns === undefined) return null\n const descriptor = svc.describe().find((candidate) => candidate.ns === ns)\n if (descriptor === undefined) return null\n const entries = filterEntries(entriesOf(descriptor.user) ?? entriesOf(descriptor.value) ?? {})\n return { writable: svc.writable, revision: descriptor.revision, entries }\n }\n\n ctx.inject(['webServer'], (wctx: Context) => {\n const web = wctx.webServer\n wctx.effect(() => web.register({\n kind: 'exact',\n path: '/subagent-library/api',\n handler: async (req: IncomingMessage, res: ServerResponse) => {\n if (req.method === 'GET') {\n if (settingsFailure !== undefined) {\n sendJson(res, 503, { ok: false, error: 'not-ready', message: settingsFailure })\n return\n }\n const view = currentView()\n if (view === null) {\n sendJson(res, 503, { ok: false, error: 'not-ready' })\n return\n }\n sendJson(res, 200, { ok: true, ...view })\n return\n }\n if (req.method !== 'POST') {\n sendJson(res, 405, { ok: false, error: 'method-not-allowed' })\n return\n }\n if (!guardWrite(req, res)) return\n const read = await readJsonBody(req)\n if (!read.ok) {\n if (read.error === 'too-large') {\n sendJson(res, 413, { ok: false, error: 'body-too-large' })\n } else {\n sendJson(res, 400, { ok: false, error: 'bad-json' })\n }\n return\n }\n const body = read.body\n const svc = settingsService\n const ns = settingsNs\n if (svc === undefined || ns === undefined) {\n sendJson(res, 503, { ok: false, error: 'not-ready' })\n return\n }\n if (!svc.writable) {\n sendJson(res, 403, { ok: false, error: 'readonly' })\n return\n }\n const rawRevision = body['expectedRevision']\n const expectedRevision = typeof rawRevision === 'number' && Number.isInteger(rawRevision) ? rawRevision : undefined\n try {\n if (body['op'] === 'delete') {\n const id = typeof body['id'] === 'string' ? body['id'] : ''\n if (!ENTRY_ID.test(id)) {\n sendJson(res, 400, { ok: false, error: 'invalid-id' })\n return\n }\n await svc.mutate(ns, [{ op: 'unset', path: ['entries', id] }], expectedRevision)\n } else if (body['op'] === 'save') {\n const entries = body['entries']\n if (typeof entries !== 'object' || entries === null || Array.isArray(entries)) {\n sendJson(res, 400, { ok: false, error: 'entries-object-required' })\n return\n }\n const candidate = entries as Record<string, unknown>\n const badKey = Object.keys(candidate).find((key) => !ENTRY_ID.test(key))\n if (badKey !== undefined) {\n sendJson(res, 400, { ok: false, error: 'invalid-entry-id', message: `entry id \"${badKey}\" is invalid` })\n return\n }\n // Validate against the plugin schema before persisting.\n Config({ ...config, entries: candidate as Record<string, Entry> })\n // A toolFilter naming an unregistered global tool makes every\n // delegation of that entry fail (tools.restrict validates loudly);\n // reject the save instead of persisting a time bomb.\n for (const entry of Object.values(candidate)) {\n const filter = (entry as Entry).toolFilter\n if (filter === undefined) continue\n for (const name of [...(filter.allow ?? []), ...(filter.deny ?? [])]) {\n if (ctx.tools.get(name) === undefined) {\n sendJson(res, 400, { ok: false, error: 'invalid-tool-name', message: `toolFilter 引用了未注册的工具 \"${name}\"` })\n return\n }\n }\n }\n // Wholesale-replace the `entries` map: the editor sends a COMPLETE\n // snapshot (fields the user cleared are absent, which is exactly\n // how a removal is expressed), while settings `update` deep-merges\n // and can never remove keys the patch dropped. Other top-level\n // user keys (e.g. subagentProvider) are preserved by spreading the\n // current raw section underneath.\n const saveDescriptor = svc.describe().find((row) => row.ns === ns)\n const userSection = (saveDescriptor?.user ?? {}) as Record<string, unknown>\n await svc.replace(ns, { ...userSection, entries: candidate }, expectedRevision)\n } else {\n sendJson(res, 400, { ok: false, error: 'unknown-op' })\n return\n }\n const view = currentView()\n if (view === null) {\n sendJson(res, 503, { ok: false, error: 'not-ready' })\n return\n }\n sendJson(res, 200, { ok: true, ...view })\n } catch (error) {\n const message = String(error)\n // SettingsConflictError carries a stable `code` property; checking the\n // property (not `instanceof`) survives the bundled module copy.\n if ((error as { code?: unknown }).code === 'SETTINGS_CONFLICT') {\n sendJson(res, 409, { ok: false, error: 'conflict' })\n } else {\n sendJson(res, 400, { ok: false, error: 'rejected', message })\n }\n }\n },\n }), 'subagent-library: settings api route')\n })\n\n // ── model-facing tools ─────────────────────────────────────────────────────\n ctx.tools.register(defineTool({\n name: 'list_subagents',\n description: 'List the named subagents available in the subagent library: each entry shows its id, role description, provider, model, background mode and tool filter (allow/deny scoping — e.g. deny:[write, edit] marks a read-only role). Call this before delegating so you can pick a matching library_id.',\n parameters: {},\n output: {\n schema: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n description: { type: 'string' },\n provider: { type: 'string' },\n model: { type: 'string' },\n backgroundMode: { type: 'string' },\n toolFilter: { type: 'string' },\n },\n additionalProperties: true,\n },\n },\n render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],\n },\n isConcurrencySafe: () => true,\n async execute() {\n if (settingsFailure !== undefined) throw new Error(settingsFailure)\n const lib = resolveConfig()\n return Object.entries(lib.entries).map(([id, entry]) => ({\n id,\n description: entry.description,\n provider: entry.provider ?? '(session default)',\n model: entry.model ?? '(session default)',\n backgroundMode: entry.backgroundMode ?? 'one-shot',\n ...(entry.toolFilter !== undefined\n ? {\n toolFilter: [\n entry.toolFilter.allow !== undefined ? `allow:[${entry.toolFilter.allow.join(', ')}]` : '',\n entry.toolFilter.deny !== undefined ? `deny:[${entry.toolFilter.deny.join(', ')}]` : '',\n ].filter(Boolean).join(' '),\n }\n : {}),\n }))\n },\n }))\n\n ctx.tools.register(defineTool({\n name: 'delegate',\n description: 'Delegate a task to a named subagent from the subagent library (see list_subagents for available entries and their roles). The child runs on the entry\\'s configured model with its role persona and tool scope. Prefer this over ad-hoc subagent calls when a library entry matches the task.',\n parameters: {\n library_id: {\n type: 'string',\n required: true,\n description: 'id of the library entry to use',\n },\n prompt: {\n type: 'string',\n required: true,\n description: 'task content delivered to the child as its first user message',\n },\n description: {\n type: 'string',\n description: 'short display label recorded for the child session',\n },\n run_in_background: {\n type: 'boolean',\n description: 'start as a background task and return immediately (continuable entries run in the background by default)',\n default: false,\n },\n },\n output: {\n schema: {\n type: 'object',\n properties: {\n kind: { type: 'string' },\n runId: { type: 'string' },\n output: { type: 'array', items: { type: 'json' } },\n jobId: { type: 'string' },\n subagentId: { type: 'string' },\n },\n additionalProperties: true,\n },\n render: (_args, value) => [{\n type: 'text',\n text: value.kind === 'background'\n ? `started background subagent task ${value.jobId}`\n : value.kind === 'continuable'\n ? `started subagent ${value.subagentId}`\n : value.kind === 'foreground'\n ? outputValueText(value.output ?? [])\n : JSON.stringify(value),\n }],\n },\n isConcurrencySafe: () => true,\n async execute(args, exec): Promise<DelegateResult> {\n if (settingsFailure !== undefined) throw new Error(settingsFailure)\n const parent = exec.agent\n if (!parent) throw new Error('delegate tool requires a calling agent (exec.agent was undefined)')\n const lib = resolveConfig()\n if (!ENTRY_ID.test(args.library_id)) throw new Error(`subagent library entry id \"${args.library_id}\" is invalid`)\n // Own-property lookup only: a plain-object prototype chain would resolve\n // ids like `constructor` to inherited functions (≠ undefined) and slip\n // past the missing-entry error into a real delegation.\n const entry = Object.hasOwn(lib.entries, args.library_id) ? lib.entries[args.library_id] : undefined\n if (entry === undefined) {\n const ids = Object.keys(lib.entries)\n throw new Error(`subagent library has no entry \"${args.library_id}\"${ids.length ? ` (available: ${ids.join(', ')})` : ' (library is empty)'}`)\n }\n\n const subagentProviderName = entry.subagentProvider ?? lib.subagentProvider\n const transport = ctx.subagents.getProvider(subagentProviderName)\n if (transport === undefined) {\n throw new Error(`subagent transport provider \"${subagentProviderName}\" is not registered (available: ${ctx.subagents.list().join(', ') || 'none'})`)\n }\n\n const continuable = entry.backgroundMode === 'continuable'\n if (continuable && transport.prepareContinuable === undefined) {\n throw new Error(`delegate: transport \"${subagentProviderName}\" does not support continuable children`)\n }\n\n // A missing maxDepth used to mean \"harness-managed\", but the harness\n // imposes no global recursion cap (resolveChildDepth checks only an\n // explicit value). Default to 3 like the official subagent tool, but\n // only when the transport can enforce it — providers without a\n // depthLimit capability stay unaffected (design decision #4, amended\n // after the red-team review).\n const maxDepth = entry.maxDepth ?? (transport.capabilities.depthLimit ? DEFAULT_MAX_DEPTH : undefined)\n if (maxDepth !== undefined) assertSubagentMaxDepth(maxDepth)\n // The one-shot capability flags (depthLimit/persona/toolFilter) describe\n // ONLY the one-shot `start` path; a continuable child is composed by the\n // continuation manager itself (persona/toolFilter applied on activation,\n // gated solely by `prepareContinuable`). Skip them for continuable runs.\n if (!continuable) {\n if (maxDepth !== undefined && !transport.capabilities.depthLimit) {\n throw new Error(`delegate: transport \"${subagentProviderName}\" cannot enforce maxDepth (no depthLimit capability)`)\n }\n if (entry.persona !== undefined && !transport.capabilities.persona) {\n throw new Error(`delegate: transport \"${subagentProviderName}\" cannot apply a persona (no persona capability)`)\n }\n if (entry.toolFilter !== undefined && entry.toolFilter.allow === undefined && entry.toolFilter.deny === undefined) {\n throw new Error(`delegate: entry \"${args.library_id}\" names a toolFilter with neither allow nor deny`)\n }\n if (entry.toolFilter !== undefined && !transport.capabilities.toolFilter) {\n throw new Error(`delegate: transport \"${subagentProviderName}\" cannot apply a tool filter (no toolFilter capability)`)\n }\n }\n\n // entry.provider/model are the LLM route + model (agentOptions), NOT the\n // subagent transport; the transport is `subagentProvider` (default spawn).\n const agentOptions = entry.provider !== undefined || entry.model !== undefined || entry.maxTokens !== undefined\n ? {\n ...(entry.provider !== undefined ? { provider: entry.provider } : {}),\n ...(entry.model !== undefined ? { model: entry.model } : {}),\n ...(entry.maxTokens !== undefined ? { maxTokens: entry.maxTokens } : {}),\n }\n : undefined\n const request: Omit<SubagentStartRequest, 'signal' | 'outputSchema'> = {\n label: args.description ?? args.library_id,\n prompt: [{ type: 'text' as const, text: args.prompt }],\n parent,\n ...(agentOptions !== undefined ? { agentOptions } : {}),\n ...(entry.persona !== undefined ? { persona: entry.persona } : {}),\n ...(entry.toolFilter !== undefined ? { toolFilter: entry.toolFilter } : {}),\n ...(maxDepth !== undefined ? { maxDepth } : {}),\n }\n\n const runInBackground = args.run_in_background === true || continuable\n if (runInBackground) {\n if (continuable) {\n return {\n kind: 'continuable',\n subagentId: (await ctx.subagents.startContinuable({\n provider: subagentProviderName,\n label: args.description ?? args.library_id,\n request,\n signal: exec.signal,\n })).childId,\n }\n }\n const jobs = ctx.get('jobs') as JobRunner | undefined\n if (jobs === undefined) {\n throw new Error('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs')\n }\n return {\n kind: 'background',\n jobId: jobs.start({\n kind: 'subagent',\n label: args.description ?? args.library_id,\n owner: parent,\n run: () => {\n const controller = new AbortController()\n return {\n cancel: (reason) => {\n controller.abort(reason ?? 'background subagent task killed')\n },\n done: settleStart(ctx.subagents.start(subagentProviderName, {\n ...request,\n signal: controller.signal,\n }), controller.signal),\n }\n },\n }),\n }\n }\n return settleForegroundRun(await ctx.subagents.start(subagentProviderName, {\n ...request,\n signal: exec.signal,\n }))\n },\n }))\n\n // ── prompt section: teach the model the library exists and how to use it ───\n ctx.systemPrompt.section({\n name: 'subagent-library',\n order: LIBRARY_SECTION_ORDER,\n text: (context) => ctx.tools.get('list_subagents', context.scope) === undefined\n ? ''\n : 'Use list_subagents to see the named subagents in the library, then delegate with the delegate tool (library_id + prompt). Library entries run on a fixed model with a role persona; prefer them over ad-hoc subagent calls when an entry matches the task.',\n })\n\n // ── /subagent command: human-facing catalog ────────────────────────────────\n const commands = ctx.get('commands')\n if (commands !== undefined) {\n commands.register({\n name: 'subagent',\n description: 'List the subagent library entries',\n handler: (): CommandResult => {\n const lib = resolveConfig()\n const ids = Object.keys(lib.entries)\n const text = ids.length === 0\n ? '子代理库为空。在 settings.yaml 的 subagent-library.entries 下添加条目(id / description / provider / model / subagentProvider / persona / toolFilter / maxDepth / backgroundMode)。'\n : `子代理库(${ids.length} 个):\\n` + ids.map((id) => {\n const entry = lib.entries[id]\n return `- ${id}: ${entry.description} [${entry.provider ?? '默认模型路由'}/${entry.model ?? '默认模型'}${entry.backgroundMode === 'continuable' ? ',可续聊' : ''}]`\n }).join('\\n')\n return { kind: 'success', text }\n },\n })\n }\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23],"mappings":";;;;;;;;;;;;;;;;;AAcA,IAAI,eAAe,MAAM;CACxB;CACA,uBAAuB,IAAI,KAAK;CAChC,YAAY,gBAAgB;AAC3B,OAAK,iBAAiB;;;;;;;;CAQvB,OAAO,QAAM,OAAO;EACnB,MAAM,OAAO,KAAK;AAClB,MAAI,KAAK,IAAIA,OAAK,CAAE,OAAM,KAAK,eAAeA,OAAK;AACnD,OAAK,IAAIA,QAAM,MAAM;EACrB,IAAI,SAAS;AACb,eAAa;AACZ,OAAI,CAAC,OAAQ;AACb,YAAS;AACT,QAAK,OAAOA,OAAK;AACjB,OAAI,KAAK,SAAS,KAAK,KAAK,SAAS,KAAM,MAAK,uBAAuB,IAAI,KAAK;;;;;;;;CAQlF,IAAI,QAAM;AACT,SAAO,KAAK,KAAK,IAAIA,OAAK;;;;;;;CAO3B,IAAI,QAAM;AACT,SAAO,KAAK,KAAK,IAAIA,OAAK;;;;;;CAM3B,OAAO;AACN,SAAO,KAAK,KAAK,MAAM;;;;;;CAMxB,UAAU;AACT,SAAO,KAAK,KAAK,SAAS;;;;;;CAM3B,SAAS;AACR,SAAO,KAAK,KAAK,QAAQ;;;;;;CAM1B,UAAU;AACT,SAAO,KAAK,KAAK,SAAS;;;;;;;;;;AAU5B,IAAI,mBAAmB,MAAM;CAC5B,uBAAuB,IAAI,KAAK;;;;;;CAMhC,OAAO,OAAO;EACb,MAAM,OAAO,KAAK;EAClB,MAAM,MAAM,QAAQ;AACpB,OAAK,IAAI,KAAK,MAAM;EACpB,IAAI,SAAS;AACb,eAAa;AACZ,OAAI,CAAC,OAAQ;AACb,YAAS;AACT,QAAK,OAAO,IAAI;AAChB,OAAI,KAAK,SAAS,KAAK,KAAK,SAAS,KA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