codeden 0.6.2 → 0.6.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/dist/cli.js +1 -1
- package/dist/drizzle/20261112140714_turn_fork_point/migration.sql +1 -0
- package/dist/drizzle/20261112140714_turn_fork_point/snapshot.json +3524 -0
- package/dist/{main-hdQfX9V6.js → main-Bx58CdV4.js} +1375 -559
- package/dist/main-Bx58CdV4.js.map +1 -0
- package/dist/{main-DZBmzxSH.js → main-CMt4z1Z9.js} +2 -2
- package/dist/{main-DZBmzxSH.js.map → main-CMt4z1Z9.js.map} +1 -1
- package/dist/{mediaType-nJs-4z5U.js → mediaType-BCz-hbZl.js} +2 -2
- package/dist/{mediaType-nJs-4z5U.js.map → mediaType-BCz-hbZl.js.map} +1 -1
- package/dist/{runner-DYf8dV43.js → runner-CiaiUWOE.js} +636 -71
- package/dist/runner-CiaiUWOE.js.map +1 -0
- package/dist/runner.js +1 -1
- package/dist/{server-test-COAiKxTV.js → server-test-b0hHPqXb.js} +3 -3
- package/dist/{server-test-COAiKxTV.js.map → server-test-b0hHPqXb.js.map} +1 -1
- package/dist/{tree-CF7Q8tXK.js → tree-31WAOm5k.js} +184 -23
- package/dist/tree-31WAOm5k.js.map +1 -0
- package/dist/web/assets/{core-Rhf-hNq6.js → core-FqX7NQzW.js} +1 -1
- package/dist/web/assets/engine-oniguruma-C5UP18m1.js +1 -0
- package/dist/web/assets/{highlighted-body-JLMTFACH-DcKwRTm5.js → highlighted-body-JLMTFACH-BMKFJRL-.js} +1 -1
- package/dist/web/assets/{highlights-DCtMC0YR.js → highlights-9yuGk1pg.js} +1 -1
- package/dist/web/assets/{index-BLggvVMT.js → index-C3QkKvUn.js} +233 -233
- package/dist/web/assets/index-CmllrYFx.css +1 -0
- package/dist/web/assets/langs-DfCgj44a.js +1 -0
- package/dist/web/assets/mermaid-WFAXDIZX-zTA5f8lD.js +1 -0
- package/dist/web/assets/{shiki-B3-ws3OK.js → shiki-Qa-y3xHo.js} +2 -2
- package/dist/web/assets/{stream-tokenizer-hKFrMxml.js → stream-tokenizer-VL43-ily.js} +1 -1
- package/dist/web/assets/{themes-Cvhh4Ovr.js → themes-Di4DO5zr.js} +2 -2
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/main-hdQfX9V6.js.map +0 -1
- package/dist/runner-DYf8dV43.js.map +0 -1
- package/dist/tree-CF7Q8tXK.js.map +0 -1
- package/dist/web/assets/engine-oniguruma-BbpT993F.js +0 -1
- package/dist/web/assets/index-JjF9o00P.css +0 -1
- package/dist/web/assets/langs-B2ZGl3f_.js +0 -1
- package/dist/web/assets/mermaid-WFAXDIZX-C2_MUy_a.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tree-CF7Q8tXK.js","names":["F","_a","util.jsonStringifyReplacer","initializer","core.$ZodAsyncError","util.finalizeIssue","core.config","safeParse","errors.$ZodRealError","validateAsync","_emoji","base64","date","datetime","number","boolean","_null","util.nullish","util.floatSafeRemainder","util.NUMBER_FORMAT_RANGES","util.codePointLength","util.getLengthableOrigin","regexes.lowercase","regexes.uppercase","util.escapeRegex","content","util.aborted","util.explicitlyAborted","core.$ZodAsyncError","util.hide","util.finalizeIssue","core.config","regexes.anyString","regexes.guid","regexes.uuid","regexes.email","regexes.emoji","regexes.nanoid","regexes.nanoidOfLength","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.e164","regexes.number","regexes.boolean","regexes.null","util.sizeCaps","util.prefixIssues","util.optionalKeys","util.cached","isObject","util.isObject","util.esc","allowsEval","util.allowsEval","util.cleanRegex","util.rawShape","util.isPlainObject","util.getEnumValues","util.escapeRegex","core.$ZodEncodeError","util.issue","util.rawShape","util.parsedType","util.stringifyPrimitive","util.joinValues","util.normalizeParams","_null","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","regexes.base64","regexes.base64url","regexes.number","regexes.integer","core.formatError","core.flattenError","util.jsonStringifyReplacer","en","core.memoizer","util.mergeDefs","core.clone","checks.overwrite","util.hide","core.standardProps","parse.parse","parse.parseAsync","parse.safeParse","parse.safeParseAsync","parse.validate","parse.validateAsync","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","processors.stringProcessor","processors.aggregateChecks","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","core._isoDateTime","core._isoDate","core._isoTime","core._isoDuration","core._string","processors.numberProcessor","checks.gt","checks.gte","checks.lt","checks.lte","checks.multipleOf","number","core._number","core._int","processors.booleanProcessor","core._boolean","processors.nullProcessor","core._null","processors.anyProcessor","core._any","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.recordProcessor","processors.enumProcessor","processors.literalProcessor","processors.transformProcessor","core.$ZodEncodeError","issue","util.issue","processors.optionalProcessor","processors.nullableProcessor","processors.defaultProcessor","util.shallowClone","processors.prefaultProcessor","processors.nonoptionalProcessor","processors.catchProcessor","core.util.constantCatch","processors.pipeProcessor","processors.readonlyProcessor","processors.lazyProcessor","processors.customProcessor","core._custom","core._refine","core._superRefine","core._isoDateTime","core._isoDate","core._coercedNumber","schemas.ZodNumber","z.string","z.iso.datetime","z.json","z.enum","z.object","z.boolean","z.int","z.url","z.enum","z.object","z.string","z.boolean","z.int","z.array","z.discriminatedUnion","z.literal","z.record","z.unknown","z\n .string","z\n .string","z.looseObject","z.string","z.number","z.object","z.boolean","z.int","z.array","z.discriminatedUnion","z.literal","z.union","z.object","z.string","z.array","z.enum","z.object","z.string","z.discriminatedUnion","z.literal","z.int","z.boolean","z.array","z.discriminatedUnion","z.object","z.literal","z.base64","z.string","z.enum","z.array","z.enum","z.object","z.literal","z.string","z.boolean","z.int","z.array","z.discriminatedUnion","z.record","z.object","z.string","z.boolean","z.enum","z.array","z.object","z.int","z.number","z\n .array","z.string","z.enum","z.iso.datetime","z.literal","z.boolean","z.array","z.discriminatedUnion","z.enum","z.object","z.string","z.preprocess","z.enum","z\n .string","z.string","z.object","z.int","z\n .object","z.number","z.array","z.boolean","z.object","z.literal","z.string","z.boolean","z.int","z.discriminatedUnion","z.object","z.enum","z.string","z.literal","z\n .string","z.array","z.discriminatedUnion","z.boolean","z.object","z.string","z.int","z.array","z.union","z.object","z.boolean","z.string","z.array","z.int","z.enum","z\n .object","z.discriminatedUnion","z.literal","z.url","z.record","z.string","z.object","z.boolean","z.int","z.enum","z.number","z.literal","z.union","z.array","Empty","z.string","z.int","z.object","z.enum","z.boolean","z.discriminatedUnion","z.literal","z.url","z.array","z\n .string","z.record","z\n .array","z.object","z.string","z.enum","z.array","z.literal","z.discriminatedUnion","z.int","z.boolean","z\n .object","z.coerce.number","z.enum","z.object","z.int","z.string","z.boolean","z.enum","z.discriminatedUnion","z.object","z.literal","z.string","z\n .object","z.array","z\n .object","z.boolean","z.int","z\n .object","z\n .enum","z.enum","z.object","z.string","z.int","z\n .string","z.enum","z.object","z.string","z.boolean","z\n .string","z\n .object","z\n .string","z\n .array","z\n .array","z.array","z.int","z.partialRecord","z.enum","z.object","z.string","z.boolean","z\n .array","z.array","z\n .string","z.number","z.int","z.record","z.union","z.literal","z.enum","z.object","z.boolean","z.string","z.int","z.url","z.array","z.coerce.number","z.enum","z.string","z.boolean","z.discriminatedUnion","z.object","z.literal","z.array","z.int","z.record","z.enum","z.object","z.string","z.boolean","z.array","z.enum","z.object","z.string","z.record","z.array","z.number","z.int","z.boolean","z.union","z.literal","z.enum","z.object","z.string","z.int","z\n .array","z\n .object","z\n .object","z.boolean","z.array","z.record","z\n .object","z.preprocess","z\n .object","z.iso.datetime","z.object","z.int","z.string","z.unknown","z.literal","z.discriminatedUnion","z.array","z.enum","z.object","z.enum","z.string","z.array","z.int","z.literal","z.discriminatedUnion","z.number","z.object","z.enum","z.discriminatedUnion","z.literal","z.string","z.boolean","z.array","z.union","z\n .object","z\n .string","z.int","z.coerce.number","z.record","z.partialRecord","z.object","z.int","z.boolean","z.enum","z.string","z.array","z\n .object","z.record","z.discriminatedUnion","z.literal","z.coerce.number","z.object","z.string","z\n .object","z.array","z\n .string","z.boolean","z.int","z.object","z.string","z.boolean","z.array","z.enum","z.int","z.number","z.coerce.number","z.discriminatedUnion","z.literal","z.object","z.int","z.enum","z.string","z.number","z.discriminatedUnion","z.literal","z.boolean","z\n .array","z.array","z.enum","z.object","z.string","z.boolean","z.int","z.record","z.array","z.enum","z.object","z.string","z.boolean","z.int","z.array","z.union","z.literal","z\n .object","z.object","z.enum","z.coerce.number","z\n .object","z.string","z.boolean","z.enum","z.object","z.boolean","z.string","z.discriminatedUnion","z.object","z.literal","z.enum","z.int","z.boolean","z.string","z.array","z.string","z.int","z.object","z.boolean","z.literal","z.discriminatedUnion","z.array","z.enum","z.unknown","z.object","z.string","z.enum","z.int","z.array","z.boolean","z.enum","z.object","z.string","z.enum","z.object","z.int","z.string","z.number","z.iso.date","z.url","z.boolean","z.array","z.record","allowsEval$1","QueueSender"],"sources":["../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/util.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/core.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/errors.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/parse.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/regexes.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/checks.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/doc.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/versions.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/schemas.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/memoizer.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/locales/en.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/registries.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/api.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/to-json-schema.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/json-schema-processors.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/errors.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/parse.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/schemas.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/iso.js","../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/coerce.js","../../../packages/contracts/src/common.ts","../../../packages/contracts/src/agent-config.ts","../../../packages/contracts/src/agent-config-hooks.ts","../../../packages/contracts/src/agent-config-loaded.ts","../../../packages/contracts/src/agent-config-mcp-test.ts","../../../packages/contracts/src/input.ts","../../../packages/contracts/src/items.ts","../../../packages/contracts/src/slash-commands.ts","../../../packages/contracts/src/agent-events.ts","../../../packages/contracts/src/entities/inbox.ts","../../../packages/contracts/src/factory.ts","../../../packages/contracts/src/entities/project.ts","../../../packages/contracts/src/work.ts","../../../packages/contracts/src/project-config.ts","../../../packages/contracts/src/provider.ts","../../../packages/contracts/src/runner/browser.ts","../../../packages/contracts/src/runner/commands.ts","../../../packages/contracts/src/workbench.ts","../../../packages/contracts/src/entities/session.ts","../../../packages/contracts/src/entities/automation.ts","../../../packages/contracts/src/entities/artifact.ts","../../../packages/contracts/src/factory-pipeline.ts","../../../packages/contracts/src/factory-api.ts","../../../packages/contracts/src/github.ts","../../../packages/contracts/src/orchestration.ts","../../../packages/contracts/src/updates.ts","../../../packages/contracts/src/voice-api.ts","../../../packages/contracts/src/settings.ts","../../../packages/contracts/src/events.ts","../../../packages/contracts/src/ws.ts","../../../packages/contracts/src/api.ts","../../../packages/contracts/src/automations-api.ts","../../../packages/contracts/src/automations-sharing.ts","../../../packages/contracts/src/browser-api.ts","../../../packages/contracts/src/desktop.ts","../../../packages/contracts/src/images-api.ts","../../../packages/contracts/src/network.ts","../../../packages/contracts/src/orchestration-api.ts","../../../packages/contracts/src/projects-api.ts","../../../packages/contracts/src/runner/events.ts","../../../packages/contracts/src/runner/messages.ts","../../../packages/contracts/src/session-files.ts","../../../packages/contracts/src/tools.ts","../../../packages/contracts/src/usage.ts","../../../packages/contracts/src/version.ts","../../runner/src/process/env.ts","../../runner/src/process/tree.ts"],"sourcesContent":["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 toZod() {\n return (schema) => schema;\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}\n// the accessor lives on a shared prototype: an own accessor makes every box a dictionary-mode object (~360 B and a slow load per read against ~100 B and an inlined getter here)\nclass Cached {\n constructor(getter) {\n this._getter = getter;\n this._value = undefined;\n }\n get value() {\n const getter = this._getter;\n if (getter !== undefined) {\n this._value = getter();\n this._getter = undefined;\n }\n return this._value;\n }\n}\nexport function cached(getter) {\n return new Cached(getter);\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 // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin.\n const tolerance = 4 * 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}\n/**\n * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.\n *\n * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.\n */\nexport function rawShape(def) {\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n return desc?.get ? desc.get.raw : desc?.value;\n}\n// where a builder reads its source's keys and descriptors, resolving only a shape a def answers for itself. A shape resolves by object spread, so only its enumerable keys are ever part of it.\nfunction sourceShape(schema) {\n return rawShape(schema._zod.def) ?? schema._zod.def.shape;\n}\n// a key whose value is not settled yet, self-caching so every read after the first gets the same one\nfunction deferProp(target, key, getter) {\n Object.defineProperty(target, key, {\n get() {\n const value = getter();\n assignProp(this, key, value);\n return value;\n },\n enumerable: true,\n configurable: true,\n });\n}\n// Writes a settled key. A plain assignment is much cheaper than `defineProperty` and produces the same descriptor, but it runs whatever setter already answers to the key — an accessor this shape deferred, or an inherited one, which `__proto__` has on every object and prototype pollution can add for any name.\nfunction putProp(target, key, value) {\n if (key in target)\n assignProp(target, key, value);\n else\n target[key] = value;\n}\n/**\n * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.\n *\n * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.\n */\nfunction mirrorShape(target, source, keys, wrap) {\n const raw = sourceShape(source);\n for (const key of keys) {\n const desc = Object.getOwnPropertyDescriptor(raw, key);\n if (!desc.enumerable)\n continue;\n if (desc.get) {\n deferProp(target, key, () => {\n const value = source._zod.def.shape[key];\n return wrap ? wrap(value, key) : value;\n });\n }\n else\n putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);\n }\n}\n// same, for a plain shape a caller passed rather than a schema's\nfunction mirrorProps(target, source) {\n for (const key of Reflect.ownKeys(source)) {\n const desc = Object.getOwnPropertyDescriptor(source, key);\n if (!desc.enumerable)\n continue;\n if (desc.get)\n deferProp(target, key, () => source[key]);\n else\n putProp(target, key, desc.value);\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` 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 !== undefined && shape[k]._zod.optout === \"optional\";\n });\n}\n// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle.\nexport const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({\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 newShape = {};\n mirrorShape(newShape, schema, maskedKeys(schema, mask));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\n// the mask keys that select something, checked against the source's shape without resolving it\nfunction maskedKeys(schema, mask) {\n const raw = sourceShape(schema);\n const keys = [];\n // `for...in` skips symbols, so a symbol in the mask would select nothing\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (mask[key])\n keys.push(key);\n }\n return keys;\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 omitted = new Set(maskedKeys(schema, mask));\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\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. Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = sourceShape(schema);\n for (const key of Reflect.ownKeys(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 return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\n// the source's keys, then the caller's overlaid on top\nfunction extended(schema, shape) {\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));\n mirrorProps(newShape, shape);\n return newShape;\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\nexport function merge(a, b) {\n if (!b?._zod?.def) {\n throw new Error(\"Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.\");\n }\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 newShape = {};\n mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));\n mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));\n const def = mergeDefs(a._zod.def, {\n shape: newShape,\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, name = \"partial\") {\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(`.${name}() cannot be used on object schemas containing refinements`);\n }\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class &&\n ((value, key) => (selected && !selected.has(key) ? value : new Class({ type: \"optional\", innerType: value }))));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));\n}\nexport function required(Class, schema, mask) {\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => \n // overwrite with non-optional\n selected && !selected.has(key) ? value : new Class({ type: \"nonoptional\", innerType: value }));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));\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). 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}\n/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */\n/** The leading size checks of `defChecks` that set an upper bound, each paired with it. */\nexport function sizeCaps(defChecks) {\n const caps = [];\n for (const ch of defChecks ?? []) {\n const d = ch._zod.def;\n // a later check may rewrite the value\n if (!/_(length|size)$|_equals$/.test(d.check))\n break;\n const max = d.maximum ?? d.length ?? d.size;\n if (max >= 0)\n caps.push([max, ch]);\n }\n return caps;\n}\nexport function attachSchema(issues, start, inst) {\n var _a;\n for (let i = start; i < issues.length; i++) {\n (_a = issues[i]).schema ?? (_a.schema = inst);\n }\n}\nexport function finalizeIssue(iss, ctx, config) {\n var _a;\n // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead.\n const traits = iss.inst?._zod?.traits;\n if (traits?.has(\"$ZodType\")) {\n if (traits.has(\"$ZodCheck\"))\n (_a = iss).schema ?? (_a.schema = iss.inst);\n else\n iss.schema = iss.inst;\n }\n // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's.\n const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(schemaError?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n // an explicit own-key copy beats object rest with excluded keys, which v8 routes through a generic runtime call; Object.keys rather than for-in so an issue pushed with a prototype does not leak inherited keys, and an own __proto__ key is dropped rather than assigned through the setter\n const full = {};\n for (const k of Object.keys(iss)) {\n if (k === \"inst\" || k === \"schema\" || k === \"continue\" || k === \"input\" || k === \"__proto__\")\n continue;\n full[k] = iss[k];\n }\n full.path ?? (full.path = []);\n full.message = message;\n if (ctx?.reportInput) {\n full.input = iss.input;\n }\n return full;\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}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\n// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters.\nexport function codePointLength(str) {\n const units = str.length;\n if (!highSurrogate.test(str))\n return units;\n let count = units;\n for (let i = 0; i < units - 1; i++) {\n if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n count--;\n i++;\n }\n }\n return count;\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////////// PROTOTYPE INSTALLERS //////////\n//\n// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see \"The three axes\" in AGENTS.md.\n/**\n * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.\n *\n * Call this from a `proto` initializer, which runs once per prototype — never per instance.\n */\nexport function members(proto, table) {\n for (const key in table) {\n const desc = Object.getOwnPropertyDescriptor(table, key);\n // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was\n if (desc.get)\n Object.defineProperty(proto, key, { ...desc, enumerable: false });\n // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()`\n else\n defineBound(proto, key, desc.value);\n }\n}\n/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */\nexport function own(inst, key, value, enumerable = true) {\n Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });\n return value;\n}\n/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */\nexport function hide(inst, key, value) {\n return own(inst, key, value, false);\n}\n/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */\nexport /*@__NO_SIDE_EFFECTS__*/ function derived(computes, table) {\n for (const key in computes) {\n const compute = computes[key];\n // an object literal's accessor is configurable and enumerable, and `members` copies the descriptor as written\n Object.defineProperty(table, key, {\n configurable: true,\n enumerable: true,\n get() {\n return own(this, key, compute(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n }\n return table;\n}\nfunction defineBound(proto, key, fn) {\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method\n return this == null ? fn : own(this, key, fn.bind(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n}\n/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */\nfunction claim(inst, sentinel) {\n const proto = Object.getPrototypeOf(inst);\n // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines.\n return sentinel in proto ? undefined : proto;\n}\n// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped.\nlet installing;\n// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation.\nlet broke = false;\nconst breaker = {\n configurable: true,\n get() {\n broke = true;\n return undefined;\n },\n};\n/**\n * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s\n * constructor, computed from the internals object itself and cached there on\n * first read. One accessor per constructor rather than one per instance.\n */\nexport function defineLazyInternal(inst, key, compute) {\n const proto = Object.getPrototypeOf(inst._zod);\n if (key in proto && installing !== inst._zod) {\n // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type.\n installing = undefined;\n return;\n }\n installing = inst._zod;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again.\n Object.defineProperty(this, key, breaker);\n const outer = broke;\n broke = false;\n try {\n const value = compute(this);\n // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included.\n if (broke)\n delete this[key];\n else\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n broke = broke || outer;\n return value;\n }\n catch (err) {\n // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read.\n delete this[key];\n broke = broke || outer;\n throw err;\n }\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n },\n });\n}\n/**\n * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own\n * data property. One accessor per constructor rather than one per instance, because an own accessor\n * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.\n */\nexport function installLazyProp(inst, key, make, enumerable) {\n const proto = claim(inst, key);\n if (!proto)\n return;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid.\n const desc = { configurable: true, writable: true, enumerable, value: undefined };\n Object.defineProperty(this, key, desc);\n // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches\n desc.value = make(this);\n Object.defineProperty(this, key, desc);\n return desc.value;\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });\n },\n });\n}\n/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */\nexport const CONSTANT_CATCH = \"~constantCatch\";\n/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */\nexport function constantCatch(value) {\n const fn = () => value;\n fn[CONSTANT_CATCH] = true;\n return fn;\n}\n","var _a;\nimport { members as installMembers } from \"./util.js\";\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\n/* Shared descriptor for installing `_zod`; defineProperty reads it\n * synchronously, so reusing one object avoids a per-instance allocation. */\nconst _zodDesc = { value: undefined, enumerable: false };\n// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error\nlet _E = \"captureStackTrace\" in Error ? Error : null;\n// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot\nfunction newError(Definition) {\n const E = _E;\n if (E) {\n const saved = E.stackTraceLimit;\n if (typeof saved === \"number\") {\n try {\n E.stackTraceLimit = 0;\n }\n catch {\n _E = null;\n return new Definition();\n }\n try {\n return new Definition();\n }\n finally {\n E.stackTraceLimit = saved;\n }\n }\n }\n return new Definition();\n}\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, \n/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */\nproto, params) {\n // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.\n const zodProto = {};\n // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.\n function Internals(def) {\n this.def = def;\n this.constr = _;\n this.traits = new Set();\n }\n Internals.prototype = zodProto;\n const protoMembers = proto;\n // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.\n const initialized = protoMembers && new WeakSet();\n function init(inst, def) {\n if (!inst._zod) {\n _zodDesc.value = new Internals(def);\n try {\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n }\n finally {\n // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.\n _zodDesc.value = undefined;\n }\n }\n else if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n if (initialized) {\n // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.\n const own = Object.getPrototypeOf(inst);\n const ctorProto = inst._zod.constr.prototype;\n let up = own;\n while (up && up !== ctorProto)\n up = Object.getPrototypeOf(up);\n const target = up ?? own;\n if (!initialized.has(target)) {\n initialized.add(target);\n installMembers(target, protoMembers);\n }\n }\n // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype\n const proto = _.prototype;\n for (const k in proto) {\n if (!Object.prototype.hasOwnProperty.call(proto, k))\n continue;\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 const inst = params?.Parent ? newError(Definition) : this;\n init(inst, def);\n const deferred = inst._zod.deferred;\n if (deferred) {\n for (const fn of deferred) {\n fn();\n }\n // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.\n inst._zod.deferred = undefined;\n }\n // Global post-processor hook. Internal: installed by `import \"zod/compile\"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.\n const pp = globalThis.__zod_globalConfig?.postProcessor;\n if (pp)\n pp(inst);\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 = /*@__PURE__*/ 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 { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\n/* Computing the message eagerly is expensive (pretty-printed JSON of all\n * issues), so defer it until first read. The accessor functions and\n * descriptors are shared across instances to keep error construction\n * cheap; the computed message is cached on the internals object. The\n * setter preserves plain assignment semantics for consumers that\n * overwrite `message`. */\nfunction _getMessage() {\n const internals = this._zod;\n internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));\n return internals.message;\n}\nfunction _setMessage(value) {\n this._zod.message = value;\n}\nconst _messageDesc = {\n get: _getMessage,\n set: _setMessage,\n enumerable: true,\n configurable: true,\n};\nconst _issuesDesc = { value: undefined, enumerable: false };\n/* Prototypes that already carry the lazy `toString`. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n // `_zod` is already non-enumerable: $constructor's init defined it with this same descriptor\n _issuesDesc.value = def;\n Object.defineProperty(inst, \"issues\", _issuesDesc);\n // Clear the shared slot; a retained `value` pins the last error's issues.\n _issuesDesc.value = undefined;\n Object.defineProperty(inst, \"message\", _messageDesc);\n /* `toString` lives as a non-enumerable lazy getter on the shared\n * prototype; on first access it caches a per-instance closure so\n * detached usage still works. */\n const proto = Object.getPrototypeOf(inst);\n if (!_installedToString.has(proto)) {\n _installedToString.add(proto);\n Object.defineProperty(proto, \"toString\", {\n configurable: true,\n enumerable: false,\n get() {\n const value = () => this.message;\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n },\n });\n }\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, undefined, {\n Parent: Error,\n});\n/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member\n * (\"toString\", \"constructor\") would otherwise read through to the prototype, and assigning\n * \"__proto__\" would hit the setter instead of creating a key. */\nfunction node(obj, key, make) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) {\n if (key === \"__proto__\") {\n Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });\n }\n else {\n obj[key] = make();\n }\n }\n return obj[key];\n}\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 node(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 // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.\n if (el === \"_errors\") {\n if (terminal)\n curr._errors.push(mapper(issue));\n i++;\n continue;\n }\n // A path element may collide with an inherited property name such as\n // \"__proto__\" or \"constructor\". Truthiness checks read the prototype\n // (so no node is created, then ._errors.push throws), and bracket\n // assignment of \"__proto__\" hits the setter instead of creating an\n // own key. Guard the read with hasOwnProperty and create the node\n // with defineProperty so any path element becomes a real own key.\n if (!Object.prototype.hasOwnProperty.call(curr, el)) {\n Object.defineProperty(curr, el, {\n value: { _errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n const node = curr[el];\n if (terminal) {\n node._errors.push(mapper(issue));\n }\n curr = node;\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;\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 // el may collide with an inherited property name (\"__proto__\",\n // \"constructor\", ...); ??= reads the prototype so the node is never\n // created and curr.errors.push throws. Guard with hasOwnProperty and\n // create the node with defineProperty so \"__proto__\" becomes a real\n // own key rather than invoking the prototype setter.\n if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {\n Object.defineProperty(curr.properties, el, {\n value: { errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_a = curr.items)[el] ?? (_a[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\";\n// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.\nfunction finalizeParams(callee, params) {\n return { callee: params?.callee ?? callee, Err: params?.Err };\n}\nexport const _parse = (_Err) => {\n const fn = (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 ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => {\n const fn = 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 ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\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 ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\n// the error is built on the first read of `error`: finalizing the issues and constructing the instance is most of a failing parse, and a caller that only branches on `success` never pays it. a getter in the literal keeps this small; the alternative, one shared accessor descriptor plus a hidden state slot, reads ~15% faster but costs ~75 B gzipped in every bundle\nfunction failure(Err, issues, ctx) {\n let error;\n return {\n success: false,\n get error() {\n if (!error) {\n error = new Err(issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n // finalizeIssue drops `input`, so the built error holds nothing; keeping the raw issues past this point pins the parsed value for the life of the result\n issues = undefined;\n ctx = undefined;\n }\n return error;\n },\n set error(e) {\n error = e;\n // a replacement makes the getter's branch unreachable, so the captures have to go here too\n issues = undefined;\n ctx = undefined;\n },\n };\n}\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 ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n// registry mirrors of the compiler's sentinels, so this module never imports the compiler\nconst COMPILE_INVALID = /* @__PURE__ */ Symbol.for(\"zod.compile.invalid\");\nconst COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for(\"zod.compile.fallback\");\n// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema.\nexport const validate = ((schema, value, _ctx) => {\n const validator = schema._zod.bag.validator;\n if (validator !== undefined) {\n if (validator(value) !== COMPILE_INVALID)\n return true;\n // a definite sentinel means the runtime would reject, so skip the re-parse; a ctx can still change the answer\n if (validator.definite === true && _ctx === undefined)\n return false;\n }\n return validateFallback(schema, value, _ctx);\n});\nfunction validateFallback(schema, value, _ctx) {\n const ctx = _ctx\n ? { ..._ctx, async: false, abortEarly: true }\n : { async: false, abortEarly: true };\n const fallbackRun = schema._zod.bag.fallbackRun;\n let result;\n if (fallbackRun) {\n // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound\n ctx[COMPILE_FALLBACK] = true;\n result = fallbackRun({ value, issues: [] }, ctx);\n }\n else {\n result = schema._zod.run({ value, issues: [] }, ctx);\n }\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length === 0;\n}\n// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw\nexport const validateAsync = async (schema, value, _ctx) => {\n const ctx = _ctx\n ? { ..._ctx, async: true, abortEarly: true }\n : { async: true, abortEarly: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length === 0;\n};\nexport const _encode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return parse(schema, value, ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n return parse(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));\n };\n return fn;\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\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-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\nexport function nanoidOfLength(length) {\n return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);\n}\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-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\n// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. The leading lookahead then demands one anchor — a pictograph, a regional indicator, or the enclosing keycap — because `\\p{Emoji_Component}` on its own covers ASCII digits, `#`, `*`, ZWJ, variation selectors and skin tone modifiers, none of which is an emoji without a base.\nconst _emoji = `^(?=[\\\\s\\\\S]*[\\\\p{Extended_Pictographic}\\\\p{Regional_Indicator}\\\\u20E3])[\\\\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}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\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_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;\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 = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro).\nexport const creditCard = /^\\d(?:[ -]?\\d){11,18}$/;\n// ISO 4217 alpha codes from the SIX list, regenerated by scripts/update-iso-4217.ts\nexport const currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/;\n// iban electronic format: 2-letter country, check digits 02-98 (the only values `98 - remainder` can produce), 11-30 bban characters\nexport const iban = /^[A-Z]{2}(?!00|01|99)\\d{2}[A-Z0-9]{11,30}$/;\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])))`;\n/** Anchors a pattern source. The interpolation lives here rather than at the call site because\n * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it\n * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */\nfunction anchor(source) {\n return new RegExp(`^${source}$`);\n}\nexport const date = /*@__PURE__*/ anchor(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 : args.seconds\n ? `${hhmm}:[0-5]\\\\d(?:\\\\.\\\\d+)?`\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 opts = [\"Z\"];\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 // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them\n const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join(\"|\")})`;\n const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\n// the unbounded form of `string()` as a literal, so every plain string shares one instance instead of building its own\nexport const anyString = /^[\\s\\S]{0,}$/;\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});\n/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */\nconst _whenHasSize = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n};\n/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */\nconst _whenHasLength = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\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.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? 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.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? 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.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 ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN\n def.value !== BigInt(0) && 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.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.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 = _whenHasSize);\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 = _whenHasSize);\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 = _whenHasSize);\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 = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted.\n const length = typeof input === \"string\" && units > def.maximum ? util.codePointLength(input) : units;\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 = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt.\n const length = typeof input === \"string\" && units >= def.minimum && units < def.minimum * 2\n ? util.codePointLength(input)\n : units;\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 = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures.\n const length = typeof input === \"string\" && units >= def.length && units <= def.length * 2\n ? util.codePointLength(input)\n : units;\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 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 // `String.prototype.includes(sub, position)` matches `sub` at `position`\n // OR LATER, so the pattern must allow at least `position` leading chars\n // (`{N,}`), not exactly `position` chars (`{N}`).\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\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.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.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 $ZodCheckProperties = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperties\", (inst, def) => {\n $ZodCheck.init(inst, def);\n util.hide(inst, Symbol.iterator, function* () {\n yield inst;\n });\n // key and schema snapshotted together: reading one live and the other cached lets a later mutation of the caller's shape object pair a stale key with a missing schema\n let entries;\n inst._zod.check = (payload) => {\n // the base schema already typed the value, so only a nullish one is rejected here: the properties read on a primitive too, matching z.property() on a string's length\n if (payload.value == null) {\n payload.issues.push({ expected: \"object\", code: \"invalid_type\", input: payload.value, inst });\n return undefined;\n }\n entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]]));\n const input = payload.value;\n let proms;\n for (const [key, schema] of entries) {\n const result = schema._zod.run({ value: input[key], issues: [] }, {});\n if (result instanceof Promise) {\n proms ?? (proms = []);\n proms.push(result.then((result) => handleCheckPropertyResult(result, payload, key)));\n }\n else {\n handleCheckPropertyResult(result, payload, key);\n }\n }\n if (proms)\n return Promise.all(proms).then(() => undefined);\n return undefined;\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.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 = [], closed = {}) {\n this.content = [];\n this.indent = 0;\n this.args = args;\n this.closed = closed;\n }\n // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it\n indented(fn) {\n this.indent += 1;\n try {\n fn(this);\n }\n finally {\n this.indent -= 1;\n }\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 content = this?.content ?? [``];\n const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(\", \")}) {\\n${content.join(\"\\n\")}\\n};`);\n return factory(...Object.values(this.closed));\n }\n}\n","export const version = {\n major: 4,\n minor: 6,\n patch: 7,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync } 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 defChecks = inst._zod.def.checks;\n // if inst is itself a checks.$ZodCheck, run it as a check\n const checks = inst._zod.traits.has(\"$ZodCheck\")\n ? [inst, ...(defChecks ?? [])]\n : defChecks?.length\n ? [...defChecks]\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 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 if (payload.memo)\n return payload;\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 util.attachSchema(payload.issues, currLen, inst);\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 util.attachSchema(payload.issues, currLen, inst);\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 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}, {\n // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", standardProps(this));\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n});\n/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */\n// a Standard Schema result only reports issues, so a failure finalizes them straight off the raw payload: no ZodError, and no lazy result to read through\nconst toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())) } : { value: r.value };\nasync function validateAsync(inst, value) {\n const ctx = { async: true };\n return toStandardResult((await inst._zod.run({ value, issues: [] }, ctx)), ctx);\n}\nexport function standardProps(inst) {\n return {\n validate: (value) => {\n const ctx = { async: false };\n try {\n const r = inst._zod.run({ value, issues: [] }, ctx);\n if (!(r instanceof Promise))\n return toStandardResult(r, ctx);\n }\n catch (_) { }\n // async function so a synchronously throwing check rejects instead of escaping validate\n return validateAsync(inst, value);\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 // a format's own pattern, else unbounded; a template literal derives the check-aware form itself\n inst._zod.pattern = def.pattern ?? regexes.anyString;\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});\n/** The `://` guard rejected the input before the URL constructor saw it. */\nexport const URL_BAD_FORMAT = 1;\n/** The URL parser rejected the input. */\nexport const URL_UNPARSEABLE = 2;\nexport function canParseURL(input) {\n try {\n if (typeof URL !== \"undefined\" && typeof URL.canParse === \"function\")\n return URL.canParse(input);\n new URL(input);\n return true;\n }\n catch {\n return false;\n }\n}\nexport function validateURL(trimmed, def) {\n if (!(\"normalize\" in def) && !(\"hostname\" in def) && !(\"protocol\" in def)) {\n return canParseURL(trimmed) || URL_UNPARSEABLE;\n }\n return parseURLObject(trimmed, def);\n}\n/** Parses a URL while preserving the non-normalizing HTTP guard. */\nexport function parseURLObject(trimmed, def) {\n // When normalize is off, require :// for http/https URLs. This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\\/\\//i.test(trimmed)) {\n return URL_BAD_FORMAT;\n }\n try {\n if (typeof URL !== \"undefined\") {\n const URLStatic = URL;\n if (typeof URLStatic.parse === \"function\")\n return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;\n }\n // @ts-ignore\n return new URL(trimmed);\n }\n catch {\n return URL_UNPARSEABLE;\n }\n}\nconst asciiTabOrNewline = /[\\t\\n\\r]/g;\n/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL(\"https://exa\\nmple.com\")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */\nexport function stripTabAndNewline(value) {\n return value.replace(asciiTabOrNewline, \"\");\n}\nexport function urlHostnameOk(url, hostname) {\n hostname.lastIndex = 0;\n return hostname.test(url.hostname);\n}\nexport function urlProtocolOk(url, protocol) {\n protocol.lastIndex = 0;\n return protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol);\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 const url = validateURL(trimmed, def);\n if (url === URL_BAD_FORMAT) {\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 if (url === URL_UNPARSEABLE) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === true) {\n payload.value = stripTabAndNewline(trimmed);\n return;\n }\n if (def.hostname && !urlHostnameOk(url, def.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 if (def.protocol && !urlProtocolOk(url, def.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 // Set the output value based on normalize flag\n payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);\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 if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))\n throw new Error(`Invalid nanoid length: ${def.length}`);\n def.pattern ?? (def.pattern = def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length));\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});\n/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL(\"http://[...]\")` parses an authority, not an address, so `@` and `\\` re-delimit it and `\"::@1\\\\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `\"::1\\n\"` validated as `::1`. */\nconst ipv6Alphabet = /^[0-9a-fA-F:.]+$/;\nexport function isValidIPv6(value) {\n if (!ipv6Alphabet.test(value))\n return false;\n return canParseURL(`http://[${value}]`);\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.check = (payload) => {\n if (!isValidIPv6(payload.value)) {\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});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport function isValidCIDRv6(value) {\n const parts = value.split(\"/\");\n if (parts.length !== 2)\n return false;\n const [address, prefix] = parts;\n if (!prefix)\n return false;\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n return false;\n if (prefixNum < 0 || prefixNum > 128)\n return false;\n return isValidIPv6(address);\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 if (!isValidCIDRv6(payload.value)) {\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}\n// lax on purpose: the quantified regexes.base64 overflows the regex stack on multi-MB input and its leading ^$| alternation leaks through template-literal composition; isValidBase64 enforces length and padding\nexport const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = base64Charset);\n $ZodStringFormat.init(inst, def);\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////////////////////////////// ZodBase64URL //////////////////////////////\n// lax on purpose: the quantified regexes.base64url overflows the regex stack on multi-MB input; isValidBase64 enforces length on the padded string\nexport const base64urlCharset = /^[A-Za-z0-9_-]*$/;\nexport function isValidBase64URL(data) {\n if (!base64urlCharset.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 = base64urlCharset);\n $ZodStringFormat.init(inst, def);\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////////////////////////////// ZodCreditCard //////////////////////////////\nconst CC_SANITIZE = /[- ]/g;\n/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */\nfunction isLuhnAlgo(digits) {\n let length = digits.length;\n let bit = 1;\n let sum = 0;\n while (length) {\n const value = digits.charCodeAt(--length) - 48;\n bit ^= 1;\n sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;\n }\n return sum % 10 === 0;\n}\nexport function isValidCreditCard(input) {\n if (!regexes.creditCard.test(input))\n return false;\n return isLuhnAlgo(input.replace(CC_SANITIZE, \"\"));\n}\nexport const $ZodCreditCard = /*@__PURE__*/ core.$constructor(\"$ZodCreditCard\", (inst, def) => {\n // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone.\n def.pattern ?? (def.pattern = regexes.creditCard);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidCreditCard(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"credit_card\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodIBAN //////////////////////////////\n// iso 7064 mod 97-10 checksum without BigInt\nfunction isIso7064Mod97(iban) {\n let remainder = 0;\n const len = iban.length;\n for (let i = 4; i < len; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n for (let i = 0; i < 4; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n return remainder === 1;\n}\nexport function isValidIBAN(input) {\n if (!regexes.iban.test(input))\n return false;\n return isIso7064Mod97(input);\n}\nexport const $ZodIBAN = /*@__PURE__*/ core.$constructor(\"$ZodIBAN\", (inst, def) => {\n // shape only — checksum is not expressible as a pattern\n def.pattern ?? (def.pattern = regexes.iban);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidIBAN(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"iban\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\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 = 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 ? String(input)\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});\n// an oversized container fails its leading size checks before any element is parsed\nfunction capSize(inst, size) {\n const caps = util.sizeCaps(inst._zod.def.checks);\n if (!caps.length)\n return;\n const cap = Math.min(...caps.map((c) => c[0]));\n const parse = inst._zod.parse;\n inst._zod.parse = (payload, ctx) => {\n const n = size(payload.value);\n if (n > cap && !ctx?.skipChecks && ctx?.direction !== \"backward\") {\n for (const [max, ch] of util.sizeCaps(inst._zod.def.checks)) {\n if (n > max && ch._zod.def.when(payload)) {\n const start = payload.issues.length;\n ch._zod.check(payload);\n // the value is still the raw input, so no later check may read it\n payload.issues[start].continue = false;\n util.attachSchema(payload.issues, start, inst);\n return payload;\n }\n }\n }\n return parse(payload, ctx);\n };\n}\nconst arraySize = (input) => (Array.isArray(input) ? input.length : -1);\nconst mapSize = (input) => (input instanceof Map ? input.size : -1);\nconst setSize = (input) => (input instanceof Set ? input.size : -1);\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 const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n const proms = [];\n const abortEarly = ctx?.abortEarly;\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 // the element's payload is authoritative here, since handleArrayResult forwards every issue; an object's is not, because it drops a failed absent optional\n if (abortEarly && result.issues.length !== 0 && util.aborted(result))\n break;\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n capSize(inst, arraySize);\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n const isPresent = key in input;\n const isOptionalOut = optout === \"optional\";\n // The middle rung means \"absence permitted, nothing supplied in its place\", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key.\n if (!isPresent && isOptionalOut && optin === \"optional\") {\n return;\n }\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (optin !== undefined && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && optin === undefined) {\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 || (optin === \"defaulted\" && !isOptionalOut)) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\n// one shared instance; a fresh [] per schema cost 56 bytes retained\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n // aliases `keys` when there are no symbols, so a string-only shape keeps one array\n const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n for (const k of allKeys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n allKeys,\n symbolKeys,\n // string-only: handleCatchall matches it against `for...in`, which never yields a symbol\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const optin = _catchall.optin;\n const optout = _catchall.optout;\n // starts at 0, not the current length: the shape phase already ran and may have aborted\n let seen = 0;\n for (const key in input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.\n if (keySet.has(key))\n continue;\n // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping.\n if (key === \"__proto__\") {\n if (t === \"never\")\n unrecognized.push(key);\n continue;\n }\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, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand.\n continue: true,\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 desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n // a cloned def carries its source's accessor, which knows the shape it answers from; adopting that keeps the clone's keys readable without running it\n const sh = desc?.get ? desc.get.raw : (def.shape ?? {});\n if (sh) {\n // Freezes the shape on first read, so its getters resolve once and every later read sees the same schemas.\n const get = () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", { value: newSh });\n get.raw = newSh;\n return newSh;\n };\n get.raw = sh;\n Object.defineProperty(def, \"shape\", { get });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const shape = zod.def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n if (!Object.prototype.hasOwnProperty.call(propValues, key)) {\n util.assignProp(propValues, key, new Set());\n }\n for (const v of field.values)\n propValues[key].add(v);\n // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it.\n if (field.optin !== undefined)\n propValues[key].add(undefined);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const proms = [];\n const shape = value.shape;\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const key of value.allKeys) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n if (key === \"__proto__\")\n continue;\n const el = shape[key];\n const optin = el._zod.optin;\n const optout = el._zod.optout;\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, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\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, abortEarly === true);\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 memo = core.globalConfig.memoizer;\n const generateFastpass = (shape) => {\n const normalized = _normalized.value;\n const syms = normalized.symbolKeys;\n // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope\n const doc = new Doc([\"payload\", \"ctx\"], { shape, inst, memo, syms });\n const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n // prefixes in place, like util.prefixIssues. newResult must land before the early return: a catchall runs after this and would otherwise write onto the caller's input\n const prefixStr = (id, k) => `\n let ${id}_ab = false;\n for (let i = 0; i < ${id}.issues.length; i++) {\n const iss = ${id}.issues[i];\n iss.path = iss.path ? [${k}, ...iss.path] : [${k}];\n payload.issues.push(iss);\n if (iss.continue !== true) ${id}_ab = true;\n }\n if (${id}_ab && ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }`;\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.allKeys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);\n for (const key of normalized.allKeys) {\n if (key === \"__proto__\")\n continue;\n const id = ids[key];\n const k = typeof key === \"symbol\" ? `syms[${syms.indexOf(key)}]` : util.esc(key);\n const isPresent = `${k} in input`;\n const schema = shape[key];\n const optin = schema?._zod?.optin;\n const isOptionalIn = optin !== undefined;\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(k)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all.\n const assign = optin === \"optional\" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;\n doc.write(`\n const ${id}_present = ${isPresent};\n if (!${id}.issues.length || ${id}_present) {\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n\n if (${assign}) {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${isPresent};\n if (${id}.issues.length) {${prefixStr(id, k)}\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 if (ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }\n }\n\n if (${id}_present) {\n newResult[${k}] = ${id}.value;\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n `);\n if (optin === \"defaulted\") {\n doc.write(`newResult[${k}] = ${id}.value;`);\n }\n else {\n doc.write(`\n if (${id}.value !== undefined || ${isPresent}) {\n newResult[${k}] = ${id}.value;\n }\n `);\n }\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone\n return doc.compile();\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, ctx?.abortEarly === true);\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.defineLazyInternal(inst, \"optin\", (zod) => zod.def.options.some((o) => o._zod.optin === \"defaulted\")\n ? \"defaulted\"\n : zod.def.options.some((o) => o._zod.optin !== undefined)\n ? \"optional\"\n : undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n if (zod.def.options.every((o) => o._zod.values)) {\n return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n if (zod.def.options.every((o) => o._zod.pattern)) {\n const patterns = zod.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 matches = [];\n for (let i = 0; i < results.length; i++) {\n if (results[i].issues.length === 0)\n matches.push(i);\n }\n if (matches.length === 1) {\n final.value = results[matches[0]].value;\n return final;\n }\n if (matches.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 matches,\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});\n/** Returns the option whose discriminator claims `value`, or throws if ambiguous. */\nexport function getDiscriminatedOption(union, value) {\n const internals = union._zod;\n let map = internals.bag.optionsMap;\n if (!map) {\n map = discriminatorMap(internals.def);\n internals.bag.optionsMap = map;\n }\n const option = map.get(value);\n if (option === null)\n throw new Error(`Ambiguous discriminator value \"${String(value)}\"`);\n return option;\n}\nfunction discriminatorMap(def) {\n const map = new Map();\n for (const option of def.options) {\n const values = option._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const value of values) {\n if (map.has(value)) {\n if (value !== undefined)\n throw new Error(`Duplicate discriminator value \"${String(value)}\"`);\n // keep the collision marked so a later member cannot reclaim it\n map.set(value, null);\n }\n else {\n map.set(value, option);\n }\n }\n }\n return map;\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.defineLazyInternal(inst, \"propValues\", (zod) => {\n const propValues = {};\n let undefinedCount = 0;\n for (const option of zod.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 \"${zod.def.options.indexOf(option)}\"`);\n if (pv[zod.def.discriminator]?.has(undefined))\n undefinedCount++;\n for (const [k, v] of Object.entries(pv)) {\n if (!Object.prototype.hasOwnProperty.call(propValues, k)) {\n util.assignProp(propValues, k, new Set());\n }\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n if (!zod.def.unionFallback && undefinedCount > 1)\n propValues[zod.def.discriminator]?.delete(undefined);\n return propValues;\n });\n // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes and lazies — are left to the map.\n def.options.forEach((option, i) => {\n const propShape = util.rawShape(option._zod.def);\n if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {\n throw new Error(`Invalid discriminated union option at index \"${i}\"`);\n }\n });\n const disc = util.cached(() => discriminatorMap(def));\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 value = input?.[def.discriminator];\n const opt = disc.value.get(value);\n // forward metadata cannot choose an encoder for an absent tag\n if (opt && (value !== undefined || ctx.direction !== \"backward\")) {\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 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()).filter((value) => disc.value.get(value) !== null),\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});\nexport function 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 if (Object.prototype.hasOwnProperty.call(newObj, \"__proto__\"))\n delete newObj.__proto__;\n for (const key of sharedKeys) {\n if (key === \"__proto__\")\n continue;\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) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key.\n const unrecKeys = new Map();\n let unrecIssue;\n const keyIssues = new Map();\n const collect = (iss, side) => {\n let keys;\n if (iss.code === \"unrecognized_keys\" && !iss.path?.length) {\n unrecIssue ?? (unrecIssue = iss);\n keys = iss.keys;\n }\n else if (iss.code === \"invalid_key\" && iss.origin === \"record\" && iss.path?.length === 1) {\n const k = String(iss.path[0]);\n if (!keyIssues.has(k))\n keyIssues.set(k, iss);\n keys = [k];\n }\n else {\n return false;\n }\n for (const k of keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k)[side] = true;\n }\n return true;\n };\n for (const iss of left.issues) {\n if (!collect(iss, \"l\"))\n result.issues.push(iss);\n }\n for (const iss of right.issues) {\n if (!collect(iss, \"r\"))\n result.issues.push(iss);\n }\n // Report only keys rejected by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length) {\n const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];\n if (aggregated.length)\n result.issues.push({ ...unrecIssue, keys: aggregated });\n for (const k of bothKeys) {\n if (!aggregated.includes(k) && keyIssues.has(k))\n result.issues.push(keyIssues.get(k));\n }\n }\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n if (util.aborted(result))\n return result;\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 const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 = memo ? memo.alloc(inst, payload, [], ctx) : [];\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 array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n // only tracked when there is a rest loop to skip\n const abortEarly = def.rest ? ctx?.abortEarly : undefined;\n let itemAborted = false;\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 if (abortEarly && !itemAborted && r.issues.length)\n itemAborted = util.aborted(r);\n }\n }\n // sound because rest is non-empty exactly when every fixed index is present, the one case handleTupleResults cannot discard an item's issues\n if (def.rest && !itemAborted) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n let seen = payload.issues.length;\n for (const el of rest) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\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 // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n if (!omittable)\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 rule, but only after `optoutStart`: the first index where the output 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 // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`.\n if (!isPresent && i >= optoutStart && items[i]._zod.optin === \"optional\") {\n final.value.length = i;\n break;\n }\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 const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 // no guard in either loop below: a record's invalid_key aborts but an enclosing intersection can reconcile it, so a stopped loop hides keys the sibling does not own and the intersection then rejects nothing\n const proms = [];\n const values = def.keyType._zod.values;\n if (values && !def.partial) {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\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 // A declared __proto__ is stripped but is not an unrecognized key.\n if (key === \"__proto__\")\n continue;\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 if (outKey === \"__proto__\")\n continue;\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 if (def.mode === \"loose\") {\n // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n payload.value[key] = input[key];\n }\n else {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n else {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection.\n let unrecognized;\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). 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 if (values) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(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 // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\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 if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\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 const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const [key, value] of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\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 capSize(inst, mapSize);\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 const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const item of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\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 capSize(inst, setSize);\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 util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const patternValues = util.getEnumValues(zod.def.entries).filter((k) => util.propertyKeyTypes.has(typeof k));\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join(\"|\")})$` : \"^[^\\\\s\\\\S]$\");\n });\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 const values = new Set(def.values);\n inst._zod.values = values;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const vals = zod.def.values;\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(vals.length\n ? `^(${vals\n .map((o) => typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o))\n .join(\"|\")})$`\n : \"^[^\\\\s\\\\S]$\");\n });\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 core.globalConfig.memoizer?.guard(inst);\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 return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(payload, result) {\n // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it.\n payload.value = result.issues.length ? undefined : result.value;\n return payload;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n inst._zod.optout = \"optional\";\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const values = zod.def.innerType._zod.values;\n return values ? new Set([...values, undefined]) : undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === undefined) {\n // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.\n if (def.innerType._zod.optin !== \"defaulted\")\n return payload;\n // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it.\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise)\n return result.then((result) => handleOptionalResult(payload, result));\n return handleOptionalResult(payload, result);\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.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.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.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazyInternal(inst, \"values\", (zod) => {\n return zod.def.innerType._zod.values ? new Set([...zod.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 = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.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 = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.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.defineLazyInternal(inst, \"values\", (zod) => {\n const v = zod.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});\nfunction handleCatchResult(payload, result, def, ctx) {\n if (!result.issues.length) {\n payload.value = result.value;\n // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property.\n if (result.memo)\n payload.memo = true;\n return payload;\n }\n // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call.\n payload.value = def.catchValue({\n ...result,\n value: payload.value,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n return payload;\n}\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.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({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleCatchResult(payload, result, def, ctx));\n }\n return handleCatchResult(payload, result, def, ctx);\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.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.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 // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it.\n if (left.issues.some((iss) => iss.code !== \"unrecognized_keys\")) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.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.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.innerType._zod.propValues);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType?._zod?.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.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 // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign.\n if (!payload.memo)\n payload.value = Object.freeze(payload.value);\n return payload;\n}\n// a leaf's pattern source with its own checks folded in: the last pattern-carrying check wins, else length bounds narrow the catch-all, else an integer format narrows the number form. the fold lives here instead of on `_zod.pattern` so a bundle without template literals never pays for it\nfunction leafPattern(schema) {\n const def = schema._zod.def;\n let pattern = def.pattern;\n let isInt = !!def.format?.includes(\"int\");\n let minimum;\n let maximum;\n for (const ch of def.checks ?? []) {\n const d = ch._zod.def;\n if (d.pattern)\n pattern = d.pattern;\n isInt || (isInt = !!d.format?.includes(\"int\"));\n const lo = d.minimum ?? d.length;\n const hi = d.maximum ?? d.length;\n if (lo !== undefined && (minimum === undefined || lo > minimum))\n minimum = lo;\n if (hi !== undefined && (maximum === undefined || hi < maximum))\n maximum = hi;\n }\n if (pattern)\n return pattern.source;\n // an empty range matches nothing at runtime, and `{8,5}` is not a legal quantifier\n if (minimum !== undefined && maximum !== undefined && minimum > maximum)\n return \"(?!)\";\n if (minimum !== undefined || maximum !== undefined)\n return regexes.string({ minimum, maximum }).source;\n const own = schema._zod.pattern;\n return (isInt && own === regexes.number ? regexes.integer : own)?.source;\n}\n// a part's pattern source. a wrapper's pattern embeds its inner pattern's source verbatim, so the folded form is substituted in place without knowing the wrapper's own composition; a union's options are joined the way the union builds its own pattern\nfunction partPattern(schema) {\n const def = schema._zod.def;\n const own = schema._zod.pattern?.source;\n // lazy resolves its inner on the internals, not the def\n const inner = def.innerType ?? schema._zod.innerType;\n if (inner) {\n const before = inner._zod.pattern?.source;\n const after = partPattern(inner);\n if (own && before && after && after !== before) {\n return own.replace(util.cleanRegex(before), () => util.cleanRegex(after));\n }\n return own;\n }\n if (def.options) {\n const sources = def.options.map(partPattern);\n if (sources.every(Boolean))\n return `^(${sources.map((s) => util.cleanRegex(s)).join(\"|\")})$`;\n }\n return leafPattern(schema);\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 const source = partPattern(part);\n if (!source) {\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n regexParts.push(util.cleanRegex(source));\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 // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.\n Object.defineProperty(inst, \"_def\", { value: 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 // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.\n return Object.defineProperty(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 }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return Object.defineProperty(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 }, \"_zod\", { value: inst._zod, enumerable: false });\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 lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, 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.defineLazyInternal(inst, \"pattern\", (zod) => zod.innerType?._zod?.pattern);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.innerType?._zod?.propValues);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.innerType?._zod?.optin ?? undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => 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","import * as util from \"./util.js\";\nexport class $ZodCyclicError extends Error {\n constructor() {\n super(`Cannot parse a reference cycle that closes through a transform`);\n this.name = \"ZodCyclicError\";\n }\n}\n/** Keyed off the context object every schema in one parse call already shares. */\nconst STATE = \"~memo\";\nconst NO_ISSUES = [];\n// a value a cycle can close through\nfunction isRef(value) {\n return value !== null && typeof value === \"object\";\n}\n// Receivers prefix paths in place, so the cache and every hand-out need their own copies.\nfunction cloneIssues(issues) {\n return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }));\n}\nconst recursive = /*@__PURE__*/ new WeakMap();\n/** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */\nconst NONE = 0;\nconst ASSUMED = 1;\nconst PROVEN = 2;\n/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */\nfunction isRecursive(inst, stack, resolve) {\n const cached = recursive.get(inst);\n if (cached !== undefined)\n return cached ? PROVEN : NONE;\n // Relative to the walk in progress, so not cached.\n if (stack.has(inst))\n return PROVEN;\n stack.add(inst);\n let result = NONE;\n const check = (child) => {\n if (result !== PROVEN && child?._zod) {\n const answer = isRecursive(child, stack, resolve);\n if (answer > result)\n result = answer;\n }\n };\n // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen\n const shape = (sh, spread) => {\n let answer = NONE;\n for (const key of Reflect.ownKeys(sh)) {\n const desc = Object.getOwnPropertyDescriptor(sh, key);\n // an object resolves its shape by spread, so a key it does not enumerate is never parsed; `z.properties` reads every own key and so keeps them all\n if (spread && !desc.enumerable)\n continue;\n // resolving runs user code, and a factory mints a fresh subtree per read, so an edge the walk can't follow counts as a cycle\n const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;\n if (child > answer)\n answer = child;\n }\n return answer;\n };\n const merge = (answer) => {\n if (answer > result)\n result = answer;\n };\n const def = inst._zod.def;\n const kind = def.type;\n switch (kind) {\n case \"object\": {\n const raw = util.rawShape(def);\n // a def with no raw shape answers `shape` from an accessor of its own, and running that can mint a whole fresh subtree\n merge(raw ? shape(raw, true) : ASSUMED);\n check(def.catchall);\n break;\n }\n case \"array\":\n check(def.element);\n break;\n case \"tuple\":\n for (const el of def.items)\n check(el);\n check(def.rest);\n break;\n case \"record\":\n case \"map\":\n check(def.keyType);\n check(def.valueType);\n break;\n case \"set\":\n check(def.valueType);\n break;\n case \"union\":\n for (const el of def.options)\n check(el);\n break;\n case \"intersection\":\n check(def.left);\n check(def.right);\n break;\n case \"optional\":\n case \"nullable\":\n case \"default\":\n case \"prefault\":\n case \"catch\":\n case \"readonly\":\n case \"nonoptional\":\n case \"promise\":\n case \"success\":\n check(def.innerType);\n break;\n case \"pipe\":\n check(def.in);\n check(def.out);\n break;\n case \"function\":\n check(def.input);\n check(def.output);\n break;\n // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly\n case \"lazy\": {\n const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : undefined);\n // walked with resolution off: one hop sees past the deferral, and a lazy that yields only another unresolved lazy is generative, so it stops there\n merge(inner ? isRecursive(inner, stack, false) : ASSUMED);\n break;\n }\n // a leaf by choice: `parts` are regex fragments, not data positions\n case \"template_literal\":\n // leaves\n case \"string\":\n case \"number\":\n case \"int\":\n case \"boolean\":\n case \"bigint\":\n case \"symbol\":\n case \"undefined\":\n case \"null\":\n case \"void\":\n case \"never\":\n case \"any\":\n case \"unknown\":\n case \"date\":\n case \"nan\":\n case \"enum\":\n case \"literal\":\n case \"file\":\n case \"transform\":\n case \"custom\":\n break;\n default: {\n // a new built-in kind becomes a compile error here\n kind;\n // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code\n for (const key in def) {\n const desc = Object.getOwnPropertyDescriptor(def, key);\n if (!desc || desc.get)\n continue;\n const value = desc.value;\n if (!value || typeof value !== \"object\")\n continue;\n if (value._zod)\n check(value);\n else if (Array.isArray(value))\n for (const el of value)\n check(el);\n }\n }\n }\n stack.delete(inst);\n return settle(inst, result);\n}\n/** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */\nfunction settle(inst, answer) {\n if (answer !== ASSUMED)\n recursive.set(inst, answer === PROVEN);\n return answer;\n}\n/**\n * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.\n * Exported for `z.compile`, which refuses to compile such a schema: cycle\n * breaking is driven from here off state keyed on the parse context, and a\n * generated fast path has no context to key on.\n */\nexport function isRecursiveSchema(inst) {\n // z.compile never parses, so nothing would ever resolve a lazy for it; it runs once and already treats a throw here as recursive\n return isRecursive(inst, new Set(), true) !== NONE;\n}\nfunction bucketFor(state, inst) {\n let bucket = state.buckets.get(inst);\n if (!bucket) {\n bucket = new WeakMap();\n state.buckets.set(inst, bucket);\n }\n return bucket;\n}\n// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving.\nlet handoff;\n// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema.\nconst open = [];\nconst memo = {\n alloc(_inst, payload, empty) {\n const bucket = handoff;\n if (!bucket)\n return empty;\n handoff = undefined;\n const entry = { value: empty, issues: null };\n bucket.set(payload.value, entry);\n open.push(entry);\n return empty;\n },\n guard(inst) {\n var _a;\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind.\n if (ctx.direction !== \"backward\" && isBackEdge(ctx, payload.value))\n throw new $ZodCyclicError();\n return base(payload, ctx);\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n attach(inst) {\n var _a;\n let isRecursiveInst;\n let rechecked = false;\n // a recursive schema is re-entered many times per parse and its bucket never changes\n let lastCtx;\n let lastBucket;\n // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically.\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n if (isRecursiveInst === undefined) {\n const walked = isRecursive(inst, new Set(), false);\n if (walked === NONE) {\n // Nothing here can ever fire, so take it back out.\n inst._zod.parse = base;\n if (inst._zod.run === wrapped)\n inst._zod.run = base;\n return base(payload, ctx);\n }\n // this parse resolves the deferred edges on its own path, so ask once more before latching\n if (walked === PROVEN || rechecked)\n isRecursiveInst = true;\n else\n rechecked = true;\n }\n const input = payload.value;\n if (!isRef(input))\n return base(payload, ctx);\n let state = ctx[STATE];\n if (!state) {\n state = { buckets: new WeakMap(), backEdges: undefined };\n ctx[STATE] = state;\n }\n let bucket;\n if (lastCtx === ctx) {\n bucket = lastBucket;\n }\n else {\n bucket = bucketFor(state, inst);\n lastCtx = ctx;\n lastBucket = bucket;\n }\n const hit = bucket.get(input);\n if (hit) {\n payload.value = hit.value;\n if (hit.issues) {\n if (hit.issues.length)\n payload.issues.push(...cloneIssues(hit.issues));\n }\n else {\n // Still being parsed: its own checks cover it, so skip them here.\n payload.memo = true;\n state.backEdges ?? (state.backEdges = new WeakSet());\n state.backEdges.add(hit.value);\n }\n return payload;\n }\n handoff = bucket;\n const depth = open.length;\n const result = base(payload, ctx);\n handoff = undefined;\n // A container that rejected its input outright allocated nothing.\n const entry = open.length > depth ? open.pop() : undefined;\n // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined.\n if (result instanceof Promise) {\n return result.then((r) => {\n if (entry)\n entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;\n return r;\n });\n }\n if (entry)\n entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;\n return result;\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n};\n/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */\nexport function memoizer() {\n return memo;\n}\n/** Whether this value is a node a back-edge resolved to before it finished. */\nexport function isBackEdge(ctx, value) {\n const backEdges = ctx[STATE]?.backEdges;\n return backEdges !== undefined && isRef(value) && backEdges.has(value);\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"characters\", verb: \"to have\" },\n file: { unit: \"bytes\", verb: \"to have\" },\n array: { unit: \"items\", verb: \"to have\" },\n set: { unit: \"items\", verb: \"to have\" },\n map: { unit: \"entries\", verb: \"to have\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"email address\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datetime\",\n date: \"ISO date\",\n time: \"ISO time\",\n duration: \"ISO duration\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n mac: \"MAC address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded string\",\n base64url: \"base64url-encoded string\",\n json_string: \"JSON string\",\n e164: \"E.164 number\",\n currency_code: \"currency code\",\n credit_card: \"credit card number\",\n iban: \"IBAN\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n // type names: missing keys = do not translate (use raw value via ?? fallback)\n const TypeDictionary = {\n // Compatibility: \"nan\" -> \"NaN\" for display\n nan: \"NaN\",\n // All other type names omitted - they fall back to raw values via ?? operator\n };\n function getTypeName(type, input) {\n if (type === \"number\" && typeof input === \"number\" && !Number.isFinite(input)) {\n return String(input);\n }\n return TypeDictionary[type] ?? type;\n }\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = getTypeName(issue.expected);\n const receivedType = util.parsedType(issue.input);\n const received = getTypeName(receivedType, issue.input);\n return `Invalid input: expected ${expected}, received ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n return `Invalid option: expected one of ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Too big: expected ${issue.origin ?? \"value\"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n return `Too big: expected ${issue.origin ?? \"value\"} to be ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Invalid string: must start with \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Invalid string: must end with \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Invalid string: must include \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Invalid string: must match pattern ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Invalid number: must be a multiple of ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Unrecognized key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Invalid key in ${issue.origin}`;\n case \"invalid_union\":\n if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {\n const opts = issue.options.map((o) => `'${o}'`).join(\" | \");\n return `Invalid discriminator value. Expected ${opts}`;\n }\n if (issue.inclusive === false) {\n return \"Invalid input: more than one option matched\";\n }\n return \"Invalid input\";\n case \"invalid_element\":\n return `Invalid value in ${issue.origin}`;\n default:\n return `Invalid input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n","var _a;\nexport const $output = /*@__PURE__*/ Symbol(\"ZodOutput\");\nexport const $input = /*@__PURE__*/ 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\";\nfunction snapshotChecks(def) {\n if (def.checks)\n def.checks = [...def.checks];\n return def;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", coerce: true, ...util.normalizeParams(params) }));\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 _creditCard(Class, params) {\n return new Class({\n type: \"string\",\n format: \"credit_card\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _iban(Class, params) {\n return new Class({\n type: \"string\",\n format: \"iban\",\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(snapshotChecks({ type: \"number\", checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", coerce: true, checks: [], ...util.normalizeParams(params) }));\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 _properties(shape, params) {\n return new checks.$ZodCheckProperties({\n check: \"properties\",\n shape,\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: 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 : util.constantCatch(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 if (!(\"input\" in _issue))\n _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 codec._zod.bag.truthy = truthyArray;\n codec._zod.bag.falsy = falsyArray;\n codec._zod.bag.case = params.case ?? \"insensitive\";\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 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\";\nimport { assignProp } from \"./util.js\";\nfunction assignProps(target, ...sources) {\n for (const source of sources) {\n for (const key of Reflect.ownKeys(source)) {\n if (Object.prototype.propertyIsEnumerable.call(source, key)) {\n assignProp(target, key, source[key]);\n }\n }\n }\n return target;\n}\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 sharedDefsExtractedFor: undefined,\n sharedEmitDoneFor: undefined,\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n intersections: [],\n deferred: [],\n external: params?.external ?? undefined,\n };\n}\n/**\n * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws\n * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a\n * custom JSON Schema was written into `json`, in which case the caller must not write its own.\n */\nexport function handleUnrepresentable(schema, ctx, json, params, message) {\n const result = typeof ctx.unrepresentable === \"function\"\n ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message })\n : ctx.unrepresentable;\n if (result === \"any\")\n return false;\n if (result === undefined || result === \"throw\")\n throw new Error(message);\n Object.assign(json, result);\n return true;\n}\n// never rename this back to `process`: bundler polyfills inject a top-level `const process` that a lexical declaration of the same name collides with (#6397)\nexport function processSchema(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 ctx.sharedDefsExtractedFor = undefined;\n ctx.sharedEmitDoneFor = undefined;\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 processSchema(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 assignProps(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}\n/** @deprecated Renamed to `processSchema`. An export alias declares no binding, so it is safe to keep. */\nexport { processSchema as process };\n// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first.\nfunction encodeJSONPointerSegment(segment) {\n return segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\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 // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once.\n if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external)\n return;\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 defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes multiple schemas map to the same seen object. 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}/${encodeJSONPointerSegment(id)}` };\n }\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#`\n if (entry[1] === root && !entry[1].schema.id) {\n return { ref: uriPrefix };\n }\n // self-contained schema\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) };\n };\n // stored cached version in `def` property 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 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 }\n }\n }\n if (ctx.external)\n ctx.sharedDefsExtractedFor = ctx.external;\n}\n/** Rewrites `anyOf: [{type: \"a\"}, {type: \"b\"}]` to `type: [\"a\", \"b\"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so \"exactly one\" and \"at least one\" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */\nfunction compactTypeUnion(schema) {\n const options = schema.anyOf;\n if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined)\n return;\n const types = [];\n for (const option of options) {\n if (!option || typeof option !== \"object\")\n return;\n // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in.\n compactTypeUnion(option);\n const keys = Object.keys(option);\n if (keys.length !== 1 || keys[0] !== \"type\")\n return;\n const type = option.type;\n for (const member of Array.isArray(type) ? type : [type]) {\n if (typeof member !== \"string\")\n return;\n if (!types.includes(member))\n types.push(member);\n }\n }\n delete schema.anyOf;\n // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string.\n schema.type = types.length === 1 ? types[0] : types;\n}\n/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`,\n * an annotation like `description` — makes a member unfoldable, so a constraint this does not\n * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */\nconst FOLDABLE_KEYS = new Set([\"type\", \"properties\", \"required\", \"additionalProperties\"]);\nconst UNION_KEYS = [\"oneOf\", \"anyOf\"];\n/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */\nfunction undeclaredConstraint(member) {\n const extra = member.additionalProperties;\n if (extra === undefined || extra === false || typeof extra !== \"object\" || extra === null)\n return null;\n return Object.keys(extra).length ? extra : null;\n}\n/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */\nfunction foldObjects(members) {\n const objects = [];\n for (const member of members) {\n // A boolean subschema is legal JSON Schema and carries no keywords to fold.\n if (typeof member !== \"object\" || member.type !== \"object\")\n return null;\n for (const key in member) {\n if (!FOLDABLE_KEYS.has(key))\n return null;\n }\n objects.push(member);\n }\n const properties = {};\n const required = new Set();\n for (const object of objects) {\n for (const key in object.properties) {\n // `in` would report a `__proto__` key as already present via the prototype chain and skip it.\n if (Object.prototype.hasOwnProperty.call(properties, key))\n continue;\n // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down.\n const parts = [];\n for (const other of objects) {\n const part = other.properties?.[key] ?? undeclaredConstraint(other);\n if (part === null || part === undefined)\n continue;\n if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part)))\n parts.push(part);\n }\n const merged = parts.length === 1\n ? parts[0]\n : (foldObjects(parts) ?? { allOf: parts });\n assignProp(properties, key, merged);\n }\n for (const key of object.required ?? [])\n required.add(key);\n }\n const folded = { type: \"object\", properties };\n if (required.size)\n folded.required = [...required];\n // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key.\n if (objects.every((object) => object.additionalProperties === false)) {\n folded.additionalProperties = false;\n }\n else {\n const constraints = [];\n for (const object of objects) {\n const constraint = undeclaredConstraint(object);\n if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))\n constraints.push(constraint);\n }\n if (constraints.length === 1)\n folded.additionalProperties = constraints[0];\n else if (constraints.length > 1)\n folded.additionalProperties = { allOf: constraints };\n }\n return folded;\n}\n/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two\n * closed object members reject each other's keys and the schema validates nothing. Zod's parser\n * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when\n * *every* side rejects it — so the emitted schema has to pool them too, and folding the members\n * into one object is the encoding that says so on every target.\n *\n * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref`\n * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it\n * keeps its reference and its own closedness rather than being inlined as a stale copy. */\nfunction foldIntersection(json) {\n const allOf = json.allOf;\n if (!Array.isArray(allOf) || allOf.length < 2)\n return;\n // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them.\n for (const key of FOLDABLE_KEYS)\n if (key in json)\n return;\n // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out.\n const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));\n let folded = null;\n if (!unions.length) {\n folded = foldObjects(allOf);\n }\n else {\n const union = unions[0];\n const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));\n if (Object.keys(union).length !== 1)\n return;\n const rest = allOf.filter((m) => m !== union);\n const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));\n if (branches.some((b) => !b))\n return;\n folded = { [keyword]: branches };\n }\n if (!folded)\n return;\n delete json.allOf;\n assignProps(json, folded);\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 assignProps(schema, refSchema);\n }\n // restore child's own properties (child wins)\n assignProps(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. This handles cases like: readonly().meta({id}).describe() 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 // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion.\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n if (ctx.target !== \"openapi-3.0\") {\n for (const entry of ctx.seen.entries()) {\n compactTypeUnion(entry[1].def ?? entry[1].schema);\n }\n }\n for (const rewrite of ctx.deferred)\n rewrite();\n // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy.\n if (ctx.intersections.length) {\n const carriers = new Map();\n for (const seen of ctx.seen.values()) {\n for (const json of [seen.schema, seen.def]) {\n const allOf = json?.allOf;\n if (!Array.isArray(allOf))\n continue;\n const existing = carriers.get(allOf);\n if (existing)\n existing.push(json);\n else\n carriers.set(allOf, [json]);\n }\n }\n for (const allOf of ctx.intersections) {\n for (const json of carriers.get(allOf) ?? [])\n foldIntersection(json);\n }\n }\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 // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs\n assignProps(result, root.defId ? root.schema : (root.def ?? root.schema));\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved 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. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt.\n const defs = ctx.external?.defs ?? {};\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\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 assignProp(defs, seen.defId, seen.def);\n }\n }\n }\n if (ctx.external)\n ctx.sharedEmitDoneFor = ctx.external;\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 each call to finalize() is functionally independent 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 def.type === \"catch\") {\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 processSchema(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 processSchema(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import * as regexes from \"./regexes.js\";\nimport { base64Charset, base64urlCharset } from \"./schemas.js\";\nimport { extractDefs, finalize, handleUnrepresentable, initializeContext, processSchema, } from \"./to-json-schema.js\";\nimport { BIGINT_FORMAT_RANGES, NUMBER_FORMAT_RANGES, assignProp, getEnumValues } from \"./util.js\";\nconst narrowMin = (agg, key, value) => {\n if (agg[key] === undefined || value > agg[key])\n agg[key] = value;\n};\nconst narrowMax = (agg, key, value) => {\n if (agg[key] === undefined || value < agg[key])\n agg[key] = value;\n};\nconst narrowBoth = (agg, value) => {\n narrowMin(agg, \"minimum\", value);\n narrowMax(agg, \"maximum\", value);\n};\nconst addDivisor = (agg, value) => {\n agg.multipleOf ?? (agg.multipleOf = []);\n if (!agg.multipleOf.includes(value))\n agg.multipleOf.push(value);\n};\nconst addPattern = (agg, pattern) => {\n agg.patterns ?? (agg.patterns = new Set());\n agg.patterns.add(pattern);\n};\nconst intersectMime = (agg, mime) => {\n agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];\n};\n// last-wins, matching the bag's historical write order; the flag keeps an integer format from being lost to a later float one\nconst setFormat = (agg, format) => {\n agg.format = format;\n if (format.includes(\"int\"))\n agg.isInt = true;\n};\nconst minContributor = (agg, def) => narrowMin(agg, \"minimum\", def.minimum);\nconst maxContributor = (agg, def) => narrowMax(agg, \"maximum\", def.maximum);\nconst formatContributor = (ranges) => (agg, def) => {\n setFormat(agg, def.format);\n const [minimum, maximum] = ranges[def.format];\n narrowMin(agg, \"minimum\", minimum);\n narrowMax(agg, \"maximum\", maximum);\n};\nconst contributors = {\n greater_than: (agg, def) => narrowMin(agg, def.inclusive ? \"minimum\" : \"exclusiveMinimum\", def.value),\n less_than: (agg, def) => narrowMax(agg, def.inclusive ? \"maximum\" : \"exclusiveMaximum\", def.value),\n multiple_of: (agg, def) => addDivisor(agg, def.value),\n number_format: formatContributor(NUMBER_FORMAT_RANGES),\n bigint_format: formatContributor(BIGINT_FORMAT_RANGES),\n min_length: minContributor,\n max_length: maxContributor,\n length_equals: (agg, def) => narrowBoth(agg, def.length),\n min_size: minContributor,\n max_size: maxContributor,\n size_equals: (agg, def) => narrowBoth(agg, def.size),\n string_format: (agg, def) => {\n setFormat(agg, def.format);\n if (def.pattern)\n addPattern(agg, def.pattern);\n if (def.format === \"base64\" || def.format === \"base64url\")\n agg.contentEncoding = def.format;\n if (def.local || def.precision === -1)\n agg.laxFormat = true;\n },\n mime_type: (agg, def) => intersectMime(agg, def.mime),\n};\nexport function aggregateChecks(schema) {\n const agg = {};\n const def = schema._zod.def;\n // a format schema is its own first check, same rule as $ZodType init\n const list = schema._zod.traits.has(\"$ZodCheck\")\n ? [schema, ...(def.checks ?? [])]\n : (def.checks ?? []);\n for (const ch of list)\n contributors[ch._zod.def.check]?.(agg, ch._zod.def);\n // reconcile with the bag so third-party onattach contributions still land; first-party residue is never tighter than the fold, so merging it back is idempotent for one and additive for the other\n const bag = schema._zod.bag;\n if (bag.minimum !== undefined)\n narrowMin(agg, \"minimum\", bag.minimum);\n if (bag.exclusiveMinimum !== undefined)\n narrowMin(agg, \"exclusiveMinimum\", bag.exclusiveMinimum);\n if (bag.maximum !== undefined)\n narrowMax(agg, \"maximum\", bag.maximum);\n if (bag.exclusiveMaximum !== undefined)\n narrowMax(agg, \"exclusiveMaximum\", bag.exclusiveMaximum);\n if (bag.multipleOf !== undefined)\n addDivisor(agg, bag.multipleOf);\n if (bag.format !== undefined) {\n agg.format ?? (agg.format = bag.format);\n if (bag.format.includes(\"int\"))\n agg.isInt = true;\n }\n if (bag.mime)\n intersectMime(agg, bag.mime);\n for (const pattern of bag.patterns ?? [])\n addPattern(agg, pattern);\n return agg;\n}\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 ====================\n// the runtime patterns are lax so parse paths never overflow the regex stack; the emitted schema swaps in the exact block forms, which zod itself never executes\nconst exactPatterns = new Map([\n [base64Charset, regexes.base64],\n [base64urlCharset, regexes.base64url],\n]);\nconst exactPattern = (p) => exactPatterns.get(p) ?? p;\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);\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 // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids\n if (format === \"time\" || laxFormat) {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const patternList = [...patterns].map(exactPattern);\n if (patternList.length === 1)\n json.pattern = patternList[0].source;\n else if (patternList.length > 1) {\n json.allOf = [\n ...patternList.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, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);\n json.type = isInt ? \"integer\" : \"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 (multipleOf) {\n // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form.\n const divisors = new Set();\n for (const divisor of multipleOf) {\n if (Number.isFinite(divisor) && divisor !== 0)\n divisors.add(Math.abs(divisor));\n else\n handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);\n }\n // chained divisors are a conjunction the keyword cannot carry alone, so extras ride an allOf, same as stacked patterns\n const [first, ...rest] = divisors;\n if (first !== undefined)\n json.multipleOf = first;\n if (rest.length)\n json.allOf = [...(json.allOf ?? []), ...rest.map((m) => ({ multipleOf: m }))];\n }\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"BigInt cannot be represented in JSON Schema\");\n};\nexport const symbolProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Symbols cannot be represented in JSON Schema\");\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 handleUnrepresentable(schema, ctx, json, params, \"Undefined cannot be represented in JSON Schema\");\n};\nexport const voidProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Void cannot be represented in JSON Schema\");\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 handleUnrepresentable(schema, ctx, json, params, \"Date cannot be represented in JSON Schema\");\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // an empty enum accepts nothing, same as z.never()\n if (values.length === 0) {\n json.not = {};\n return;\n }\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 // a literal with no values accepts nothing, same as z.never()\n if (def.values.length === 0) {\n json.not = {};\n return;\n }\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n // a custom schema replaces the whole literal, so there is nothing left to accumulate\n if (handleUnrepresentable(schema, ctx, json, params, \"Literal `undefined` cannot be represented in JSON Schema\"))\n return;\n // otherwise do not add to vals\n }\n else if (typeof val === \"bigint\") {\n if (handleUnrepresentable(schema, ctx, json, params, \"BigInt literals cannot be represented in JSON Schema\"))\n return;\n vals.push(Number(val));\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 handleUnrepresentable(schema, ctx, json, params, \"NaN cannot be represented in JSON Schema\");\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 _json.type = \"string\";\n _json.format = \"binary\";\n _json.contentEncoding = \"binary\";\n const { minimum, maximum, mime } = aggregateChecks(schema);\n if (minimum !== undefined)\n _json.minLength = minimum;\n if (maximum !== undefined)\n _json.maxLength = maximum;\n if (!mime)\n return;\n // an empty intersection means the mime checks share no value, so nothing passes at runtime; `anyOf` must be non-empty, so the false schema is `not: {}`\n if (mime.length === 0)\n _json.not = {};\n else if (mime.length === 1)\n _json.contentMediaType = mime[0];\n // only contentMediaType differs, so the shared props stay at the root\n else\n _json.anyOf = mime.map((m) => ({ contentMediaType: m }));\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Custom types cannot be represented in JSON Schema\");\n};\nexport const functionProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Function types cannot be represented in JSON Schema\");\n};\nexport const transformProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Transforms cannot be represented in JSON Schema\");\n};\nexport const mapProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Map cannot be represented in JSON Schema\");\n};\nexport const setProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Set cannot be represented in JSON Schema\");\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 } = aggregateChecks(schema);\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 = processSchema(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\n// Transform and catch set `optin = \"optional\"` at runtime so the parser lets them observe an\n// absent key, but their declared input type stays required. An input JSON Schema describes the\n// declared type, so resolve past them to the schema that actually carries the optionality.\n// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see\n// wiki/optionality.md, \"The JSON Schema emitter reads the *static* value\".\nfunction inputOptin(schema) {\n const def = schema._zod.def;\n if (def.type === \"pipe\" && def.in._zod.traits.has(\"$ZodTransform\")) {\n return inputOptin(def.out);\n }\n if (def.type === \"catch\") {\n return inputOptin(def.innerType);\n }\n return schema._zod.optin;\n}\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const shape = def.shape;\n // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires\n const symbolKeys = Object.getOwnPropertySymbols(shape);\n if (symbolKeys.length &&\n handleUnrepresentable(schema, ctx, json, params, \"Symbol keys cannot be represented in JSON Schema\")) {\n return;\n }\n json.type = \"object\";\n json.properties = {};\n for (const key in shape) {\n // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into\n assignProp(json.properties, key, processSchema(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n }));\n }\n // required keys\n const requiredKeys = [];\n for (const key of Object.keys(shape)) {\n const field = def.shape[key];\n if (ctx.io === \"input\" ? inputOptin(field) === undefined : field._zod.optout === undefined) {\n requiredKeys.push(key);\n }\n }\n if (requiredKeys.length > 0) {\n json.required = 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 = processSchema(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). This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => processSchema(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 = processSchema(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = processSchema(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 // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`.\n ctx.intersections.push(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) => processSchema(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? processSchema(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n let minItems = def.items.length;\n while (minItems > 0) {\n const item = def.items[minItems - 1];\n const optional = ctx.io === \"input\" ? inputOptin(item) !== undefined : item._zod.optout === \"optional\";\n if (!optional)\n break;\n minItems--;\n }\n const maxItems = def.items.length;\n const isClosed = !def.rest;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (isClosed) {\n json.items = false;\n }\n else if (rest) {\n json.items = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\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 if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else {\n json.items = prefixItems;\n if (isClosed) {\n json.additionalItems = false;\n }\n else if (rest) {\n json.additionalItems = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n // explicit user-defined length checks take precedence\n const { minimum, maximum } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\n/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the\n * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key\n * behind a wrapper only carries its own `type` before then, and a union key only has its branches.\n *\n * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather\n * than carried over: keeping them beside `type: \"string\"` reproduces the match-nothing schema this\n * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)`\n * accepts `\"3\"` — which is the deliberate trade, since throwing on it would reject an ordinary schema\n * outright. */\nfunction stringifyKeyNames(bySchema, json, visited) {\n // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`.\n if (json.$ref) {\n // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again\n if (visited.has(json))\n return json;\n visited.add(json);\n const def = bySchema.get(json)?.def;\n if (!def)\n return json;\n const inlined = stringifyKeyNames(bySchema, def, visited);\n return inlined === def ? json : inlined;\n }\n for (const keyword of [\"anyOf\", \"oneOf\"]) {\n const branches = json[keyword];\n if (!Array.isArray(branches))\n continue;\n const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));\n // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id`\n if (mapped.some((branch, i) => branch !== branches[i]))\n json = { ...json, [keyword]: mapped };\n }\n // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric\n const types = Array.isArray(json.type) ? json.type : [json.type];\n const numericType = !types.includes(\"string\") && types.some((t) => t === \"number\" || t === \"integer\");\n // a heterogeneous key carries no type at all, so its numeric members are caught here instead\n const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);\n if (!numericType && !values?.some((v) => typeof v === \"number\"))\n return json;\n const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;\n if (rest.enum)\n rest.enum = rest.enum.map((v) => (typeof v === \"number\" ? String(v) : v));\n else if (typeof rest.const === \"number\")\n rest.const = String(rest.const);\n // a heterogeneous key keeps its absent type: the stringified members already say what a key may be\n if (!numericType)\n return rest;\n rest.type = \"string\";\n if (!values)\n rest.pattern = (types.includes(\"number\") ? regexes.number : regexes.integer).source;\n return rest;\n}\n/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */\nconst pendingRecords = new WeakMap();\nfunction rewriteKeyNames(ctx) {\n // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it.\n const bySchema = new Map();\n for (const entry of ctx.seen.values()) {\n if (entry.def && !bySchema.has(entry.schema))\n bySchema.set(entry.schema, entry);\n }\n const rewrites = new Map();\n for (const record of pendingRecords.get(ctx) ?? []) {\n const seen = ctx.seen.get(record);\n const names = (seen?.def ?? seen?.schema)?.propertyNames;\n if (!names || names === true || rewrites.has(names))\n continue;\n const rewritten = stringifyKeyNames(bySchema, names, new Set());\n if (rewritten !== names)\n rewrites.set(names, rewritten);\n }\n if (!rewrites.size)\n return;\n // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together\n for (const entry of ctx.seen.values()) {\n for (const carrier of [entry.schema, entry.def]) {\n const rewritten = carrier && rewrites.get(carrier.propertyNames);\n if (rewritten)\n carrier.propertyNames = rewritten;\n }\n }\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. This correctly represents \"only validate keys matching the pattern\" semantics and composes well with allOf (intersections)\n const keyType = def.keyType;\n const patterns = aggregateChecks(keyType).patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = processSchema(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n assignProp(json.patternProperties, exactPattern(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 = processSchema(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n let pending = pendingRecords.get(ctx);\n if (!pending) {\n pending = [];\n pendingRecords.set(ctx, pending);\n ctx.deferred.push(() => rewriteKeyNames(ctx));\n }\n pending.push(schema);\n }\n json.additionalProperties = processSchema(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 // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined.\n const omittableOnInput = ctx.io === \"input\" && inputOptin(def.valueType) !== undefined;\n if (keyValues && !def.partial && !omittableOnInput) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues.map(String);\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = processSchema(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 processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\n/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON.\n * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other\n * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */\nconst UNREPRESENTABLE_DEFAULT = Symbol();\nfunction serializeDefaultValue(value, schema, ctx, json, params) {\n let unrepresentable = false;\n const serialized = JSON.stringify(value, (_, val) => {\n if (typeof val !== \"bigint\")\n return val;\n unrepresentable = true;\n return null;\n });\n if (!unrepresentable)\n return JSON.parse(serialized);\n handleUnrepresentable(schema, ctx, json, params, \"BigInt defaults cannot be represented in JSON Schema\");\n return UNREPRESENTABLE_DEFAULT;\n}\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json.default = value;\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io !== \"input\")\n return;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json._prefault = value;\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(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 handleUnrepresentable(schema, ctx, json, params, \"Dynamic catch values are not supported in JSON Schema\");\n return;\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 processSchema(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 processSchema(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 processSchema(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 processSchema(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 processSchema(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 processSchema(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 assignProp(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 processSchema(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\n/* Prototypes that already carry the lazy helper methods. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\n/* Helper methods live as non-enumerable lazy getters on the shared\n * prototype instead of own properties on every instance. On first\n * access the getter allocates the per-instance closure and caches it\n * as a non-enumerable own property, so detached usage still works and\n * the allocation only happens for methods actually touched. */\nfunction _lazyMethod(proto, key, make) {\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const value = make(this);\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n },\n });\n}\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n const proto = Object.getPrototypeOf(inst);\n if (_installedErrorProtos.has(proto))\n return;\n _installedErrorProtos.add(proto);\n _lazyMethod(proto, \"format\", (self) => (mapper) => core.formatError(self, mapper));\n _lazyMethod(proto, \"flatten\", (self) => (mapper) => core.flattenError(self, mapper));\n _lazyMethod(proto, \"addIssue\", (self) => (issue) => {\n self.issues.push(issue);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n _lazyMethod(proto, \"addIssues\", (self) => (issues) => {\n self.issues.push(...issues);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n Object.defineProperty(proto, \"isEmpty\", {\n configurable: true,\n enumerable: false,\n get() {\n return this.issues.length === 0;\n },\n });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, undefined, {\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);\nexport { validate, validateAsync } from \"../core/index.js\";\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 * as regexes from \"../core/regexes.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport en from \"../locales/en.js\";\nimport * as checks from \"./checks.js\";\nimport * as parse from \"./parse.js\";\n// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present.\nfunction _ensureDefaultLocale() {\n if (!core.globalConfig.localeError)\n core.config(en());\n}\n// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first\nfunction _ensureDefaultMemoizer() {\n if (!core.globalConfig.memoizer)\n core.config({ memoizer: core.memoizer() });\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n _ensureDefaultLocale();\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n return inst;\n}, {\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) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and 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, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n },\n // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", {\n ...core.standardProps(this),\n jsonSchema: {\n input: createStandardJSONSchemaMethod(this, \"input\"),\n output: createStandardJSONSchemaMethod(this, \"output\"),\n },\n });\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n parse: function _parse(data, params) {\n return parse.parse(this, data, params, { callee: _parse });\n },\n parseAsync: async function _parseAsync(data, params) {\n return await parse.parseAsync(this, data, params, { callee: _parseAsync });\n },\n safeParse(data, params) {\n return parse.safeParse(this, data, params);\n },\n async safeParseAsync(data, params) {\n return parse.safeParseAsync(this, data, params);\n },\n // `spa` is an alias: same function object as `safeParseAsync`, as before.\n get spa() {\n return this?.safeParseAsync;\n },\n set spa(value) {\n util.own(this, \"spa\", value);\n },\n validate(data, params) {\n return parse.validate(this, data, params);\n },\n validateAsync(data, params) {\n return parse.validateAsync(this, data, params);\n },\n encode: function _encode(data, params) {\n return parse.encode(this, data, params, { callee: _encode });\n },\n decode: function _decode(data, params) {\n return parse.decode(this, data, params, { callee: _decode });\n },\n encodeAsync: async function _encodeAsync(data, params) {\n return await parse.encodeAsync(this, data, params, { callee: _encodeAsync });\n },\n decodeAsync: async function _decodeAsync(data, params) {\n return await parse.decodeAsync(this, data, params, { callee: _decodeAsync });\n },\n safeEncode(data, params) {\n return parse.safeEncode(this, data, params);\n },\n safeDecode(data, params) {\n return parse.safeDecode(this, data, params);\n },\n async safeEncodeAsync(data, params) {\n return parse.safeEncodeAsync(this, data, params);\n },\n async safeDecodeAsync(data, params) {\n return parse.safeDecodeAsync(this, data, params);\n },\n toJSONSchema(params) {\n return createToJSONSchemaMethod(this, {})(params);\n },\n // Reads through to the registry on every access, so it must not cache.\n get description() {\n return core.globalRegistry.get(this)?.description;\n },\n // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property.\n get _def() {\n return this._zod.def;\n },\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}, \n/*@__PURE__*/ util.derived({\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n minLength: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxLength: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n}, {\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}));\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n}, {\n email(params) {\n return this.check(core._email(ZodEmail, params));\n },\n url(params) {\n return this.check(core._url(ZodURL, params));\n },\n jwt(params) {\n return this.check(core._jwt(ZodJWT, params));\n },\n emoji(params) {\n return this.check(core._emoji(ZodEmoji, params));\n },\n guid(params) {\n return this.check(core._guid(ZodGUID, params));\n },\n uuid(params) {\n return this.check(core._uuid(ZodUUID, params));\n },\n uuidv4(params) {\n return this.check(core._uuidv4(ZodUUID, params));\n },\n uuidv6(params) {\n return this.check(core._uuidv6(ZodUUID, params));\n },\n uuidv7(params) {\n return this.check(core._uuidv7(ZodUUID, params));\n },\n nanoid(params) {\n return this.check(core._nanoid(ZodNanoID, params));\n },\n cuid(params) {\n return this.check(core._cuid(ZodCUID, params));\n },\n cuid2(params) {\n return this.check(core._cuid2(ZodCUID2, params));\n },\n ulid(params) {\n return this.check(core._ulid(ZodULID, params));\n },\n base64(params) {\n return this.check(core._base64(ZodBase64, params));\n },\n base64url(params) {\n return this.check(core._base64url(ZodBase64URL, params));\n },\n xid(params) {\n return this.check(core._xid(ZodXID, params));\n },\n ksuid(params) {\n return this.check(core._ksuid(ZodKSUID, params));\n },\n ipv4(params) {\n return this.check(core._ipv4(ZodIPv4, params));\n },\n ipv6(params) {\n return this.check(core._ipv6(ZodIPv6, params));\n },\n cidrv4(params) {\n return this.check(core._cidrv4(ZodCIDRv4, params));\n },\n cidrv6(params) {\n return this.check(core._cidrv6(ZodCIDRv6, params));\n },\n e164(params) {\n return this.check(core._e164(ZodE164, params));\n },\n datetime(params) {\n return this.check(core._isoDateTime(ZodISODateTime, params));\n },\n date(params) {\n return this.check(core._isoDate(ZodISODate, params));\n },\n time(params) {\n return this.check(core._isoTime(ZodISOTime, params));\n },\n duration(params) {\n return this.check(core._isoDuration(ZodISODuration, params));\n },\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 ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n ZodStringFormat.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: regexes.httpProtocol,\n hostname: 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 ZodCreditCard = /*@__PURE__*/ core.$constructor(\"ZodCreditCard\", (inst, def) => {\n core.$ZodCreditCard.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function creditCard(params) {\n return core._creditCard(ZodCreditCard, params);\n}\nexport const ZodIBAN = /*@__PURE__*/ core.$constructor(\"ZodIBAN\", (inst, def) => {\n core.$ZodIBAN.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function iban(params) {\n return core._iban(ZodIBAN, 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\", regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", regexes.hex, _params);\n}\nexport function currencyCode(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"currency_code\", regexes.currencyCode, _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 inst.isFinite = true;\n}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => {\n const { minimum, exclusiveMinimum } = processors.aggregateChecks(inst);\n return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY);\n },\n maxValue: (inst) => {\n const { maximum, exclusiveMaximum } = processors.aggregateChecks(inst);\n return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY);\n },\n isInt: (inst) => {\n const { isInt, multipleOf } = processors.aggregateChecks(inst);\n return !!isInt || !!multipleOf?.some(Number.isSafeInteger);\n },\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\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}));\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}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxValue: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\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 gt(value, params) {\n return this.check(checks.gt(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 positive(params) {\n return this.check(checks.gt(BigInt(0), params));\n },\n negative(params) {\n return this.check(checks.lt(BigInt(0), params));\n },\n nonpositive(params) {\n return this.check(checks.lte(BigInt(0), params));\n },\n nonnegative(params) {\n return this.check(checks.gte(BigInt(0), params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\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});\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\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}, \n/*@__PURE__*/ util.derived({\n minDate: (inst) => {\n const { minimum } = processors.aggregateChecks(inst);\n return minimum ? new Date(minimum) : null;\n },\n maxDate: (inst) => {\n const { maximum } = processors.aggregateChecks(inst);\n return maximum ? new Date(maximum) : null;\n },\n}, {}));\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n _ensureDefaultMemoizer();\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}, {\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});\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 _ensureDefaultMemoizer();\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.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n}, {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n // `mergeDefs` rather than a spread: spreading reads `shape`, and resolving it can mint a whole fresh subtree\n return this.clone(util.mergeDefs(this._zod.def, { catchall: catchall }));\n },\n passthrough() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n loose() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n strict() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: never() }));\n },\n strip() {\n return this.clone(util.mergeDefs(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 exactPartial(...args) {\n return util.partial(ZodExactOptional, this, args[0], \"exactPartial\");\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\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: 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 _ensureDefaultMemoizer();\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}, {\n rest(rest) {\n return this.clone({\n ...this._zod.def,\n rest: rest,\n });\n },\n partial() {\n const def = this._zod.def;\n // a refinement was authored against the full arity; partialing would run it on a shorter array\n if (def.checks?.length)\n throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n return this.clone({\n ...def,\n items: def.items.map((item) => new ZodOptional({ type: \"optional\", innerType: item })),\n });\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 _ensureDefaultMemoizer();\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 return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n partial: true,\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 _ensureDefaultMemoizer();\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 _ensureDefaultMemoizer();\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 // reuse the parsed value set so a numeric TS enum's reverse-mapping keys stay out\n inst.options = [...inst._zod.values];\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 _ensureDefaultMemoizer();\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 if (!(\"input\" in _issue))\n _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 return payload;\n });\n }\n payload.value = output;\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 : core.util.constantCatch(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;\nexport const ZodInstanceOf = /*@__PURE__*/ core.$constructor(\"ZodInstanceOf\", (inst, def) => {\n ZodCustom.init(inst, def);\n}, {\n properties(shape, params) {\n // asserts in place, so the narrowed output type is truthful without a wrapper\n return this.check(core._properties(shape, params));\n },\n});\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodInstanceOf({\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 * as core from \"../core/index.js\";\nimport { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from \"./schemas.js\";\nexport { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from \"./schemas.js\";\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n return core._coercedDate(schemas.ZodDate, params);\n}\n","import { z } from \"zod\";\n\n/** Opaque identifier (UUIDs in practice, but never parsed). */\nexport const Id = z.string().min(1).max(200);\nexport type Id = z.infer<typeof Id>;\n\n/** UTC ISO-8601 timestamp, e.g. `2026-11-07T10:24:00.000Z`. */\nexport const Timestamp = z.iso.datetime();\nexport type Timestamp = z.infer<typeof Timestamp>;\n\n/** Arbitrary JSON value (tool inputs, structured results). */\nexport const JsonValue = z.json();\nexport type JsonValue = z.infer<typeof JsonValue>;\n\n/** The three agent roles (§8.1). All are the same kind of session with different tools/prompts. */\nexport const Role = z.enum([\"orchestrator\", \"pm\", \"agent\"]);\nexport type Role = z.infer<typeof Role>;\n\n/**\n * Permission levels of an agent session (§11.2), mapped onto each provider's native enforcement.\n * Shown in the UI as \"Permissions\"; stored as `autonomy`.\n * - `read_only`: reads and runs checks, but never edits files, commits or pushes. Needs a\n * provider with `ProviderCapabilities.readOnly`.\n * - `supervised`: every edit and command asks.\n * - `auto`: edits and normal commands in the worktree run freely; risky actions ask (default).\n * - `full`: no approvals inside the worktree.\n */\nexport const AutonomyLevel = z.enum([\"read_only\", \"supervised\", \"auto\", \"full\"]);\nexport type AutonomyLevel = z.infer<typeof AutonomyLevel>;\n\n/** Reasoning effort. Each model advertises the subset it supports (see `ModelInfo.efforts`). */\nexport const ReasoningEffort = z.enum([\"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"]);\nexport type ReasoningEffort = z.infer<typeof ReasoningEffort>;\n\n/**\n * Provider identifier such as `claude`, `codex`, `opencode` or `fake`. Deliberately an open string:\n * UI and orchestration must read capability flags, never branch on the id (Principle 5).\n */\nexport const ProviderId = z.string().regex(/^[a-z][a-z0-9-]{0,39}$/);\nexport type ProviderId = z.infer<typeof ProviderId>;\n\n/**\n * What kind of failure an agent turn hit, as the provider adapter classified it, so CodeDen can\n * recover by itself where waiting helps:\n * - `transient`: overloaded or failing API, a dropped connection, the agent CLI exiting; trying\n * again shortly may work.\n * - `usage_limit`: the account's usage limit is reached; it works again at `retryAt`.\n * - `context_full`: the conversation no longer fits the model's context window.\n * - `auth`: the provider's login or credentials need the user.\n * - `fatal`: anything else; retrying the same turn won't help.\n */\nexport const ErrorKind = z.enum([\"transient\", \"usage_limit\", \"context_full\", \"auth\", \"fatal\"]);\nexport type ErrorKind = z.infer<typeof ErrorKind>;\n\n/** Structured error carried by events, results and entities. */\nexport const ErrorInfo = z.object({\n /** Machine-readable code, e.g. `provider_crashed`, `not_found`. */\n code: z.string().optional(),\n /** Human-readable message, safe to show in the UI (never contains tokens). */\n message: z.string(),\n /** Whether retrying the same operation may succeed. */\n retryable: z.boolean().optional(),\n /** Optional extra detail (stack trace excerpt, stderr tail). */\n detail: z.string().optional(),\n /** How a failed agent turn can be recovered from; absent where nobody classified it. */\n kind: ErrorKind.optional(),\n /** For `usage_limit`: when the limit resets, if the provider said. */\n retryAt: Timestamp.optional(),\n});\nexport type ErrorInfo = z.infer<typeof ErrorInfo>;\n\n/** Link to a GitHub issue. */\nexport const GitHubIssueRef = z.object({\n number: z.int().positive(),\n url: z.url(),\n title: z.string().optional(),\n});\nexport type GitHubIssueRef = z.infer<typeof GitHubIssueRef>;\n\n/** Link to a GitHub pull request. */\nexport const GitHubPrRef = z.object({\n number: z.int().positive(),\n url: z.url(),\n state: z.enum([\"draft\", \"open\", \"closed\", \"merged\"]),\n title: z.string().optional(),\n});\nexport type GitHubPrRef = z.infer<typeof GitHubPrRef>;\n\n/** Hours of the day during which something must not run or speak, e.g. `22:00`-`07:00`. */\nexport const QuietHours = z.object({\n start: z.string().regex(/^([01]\\d|2[0-3]):[0-5]\\d$/),\n end: z.string().regex(/^([01]\\d|2[0-3]):[0-5]\\d$/),\n /** IANA timezone; defaults to the machine's timezone when omitted. */\n timezone: z.string().optional(),\n});\nexport type QuietHours = z.infer<typeof QuietHours>;\n","import { z } from \"zod\";\nimport { Id, Timestamp } from \"./common\";\n\n/**\n * Agent configuration screens (§12.4): each provider's own memory files, skills, subagents,\n * MCP servers and hooks (`agent-config-hooks.ts`), edited in place in their native files with\n * a diff preview and a backup before every overwrite or delete. Routes live under\n * `/api/agent-config`.\n */\n\nexport const AgentConfigProvider = z.enum([\"claude\", \"codex\"]);\nexport type AgentConfigProvider = z.infer<typeof AgentConfigProvider>;\n\n/** Agent-config screens that exist only for some providers. */\nexport interface AgentConfigFeatures {\n /** CodeDen lists and edits this provider's hooks (`/api/agent-config/hooks`). */\n hooks: boolean;\n}\n\n/**\n * Which optional agent-config screens each provider has. The UI reads this to decide which\n * tabs and choices to offer, and never branches on a provider id (Principle 5).\n */\nexport const agentConfigFeatures: Record<AgentConfigProvider, AgentConfigFeatures> = {\n claude: { hooks: true },\n codex: { hooks: false },\n};\n\n/** The providers that have a given agent-config feature. */\nexport const providersWith = (feature: keyof AgentConfigFeatures): AgentConfigProvider[] =>\n AgentConfigProvider.options.filter((p) => agentConfigFeatures[p][feature]);\n\n/**\n * - `memory`: CLAUDE.md / CLAUDE.local.md / AGENTS.md files.\n * - `rule`: `.claude/rules/**.md`.\n * - `auto_memory`: files in Claude's auto-memory folder (`MEMORY.md` is the index).\n * - `skill`: a skill's `SKILL.md`. - `subagent`: a subagent definition.\n */\nexport const AgentConfigKind = z.enum([\"memory\", \"rule\", \"auto_memory\", \"skill\", \"subagent\"]);\nexport type AgentConfigKind = z.infer<typeof AgentConfigKind>;\n\n/** `user`: the user's home config. `project`: shared in the repo. `local`: personal, per project. */\nexport const AgentConfigScope = z.enum([\"user\", \"project\", \"local\"]);\nexport type AgentConfigScope = z.infer<typeof AgentConfigScope>;\n\n/**\n * Where a file lives: `home` (relative to the user's home), `project` (relative to a\n * project's checkout) or `auto_memory` (relative to the project's Claude auto-memory folder).\n * Only known agent-config locations are accepted (CLAUDE.md, AGENTS.md, rules, skills,\n * subagents, auto memory); anything else is refused.\n */\nexport const AgentConfigLocator = z.object({\n root: z.enum([\"home\", \"project\", \"auto_memory\"]),\n /** Required for `project` and `auto_memory`. */\n projectId: Id.optional(),\n /** Relative to the root, `/`-separated. */\n path: z.string().min(1).max(1_000),\n});\nexport type AgentConfigLocator = z.infer<typeof AgentConfigLocator>;\n\n/** One discovered file. */\nexport const AgentConfigFile = AgentConfigLocator.extend({\n provider: AgentConfigProvider,\n kind: AgentConfigKind,\n scope: AgentConfigScope,\n /** Display name: the file name, or the skill/subagent name. */\n name: z.string(),\n /** `description` from the front matter (skills, subagents). */\n description: z.string().optional(),\n absolutePath: z.string(),\n exists: z.boolean(),\n sizeBytes: z.int().nonnegative(),\n modifiedAt: Timestamp.nullable(),\n /** Loaded only when the agent reads files in that folder (nested CLAUDE.md). */\n onDemand: z.boolean().optional(),\n});\nexport type AgentConfigFile = z.infer<typeof AgentConfigFile>;\n\n/** `GET /api/agent-config/files?projectId=&provider=&kind=`. */\nexport const AgentConfigListQuery = z.object({\n projectId: Id.optional(),\n provider: AgentConfigProvider.optional(),\n kind: AgentConfigKind.optional(),\n});\nexport type AgentConfigListQuery = z.infer<typeof AgentConfigListQuery>;\n\nexport const AgentConfigListResponse = z.object({\n files: z.array(AgentConfigFile),\n /** Claude's auto-memory folder for the project (when `projectId` was given). */\n autoMemoryDir: z.string().nullable(),\n});\nexport type AgentConfigListResponse = z.infer<typeof AgentConfigListResponse>;\n\n/** `GET /api/agent-config/file?root=&projectId=&path=`. Missing files read as empty. */\nexport const AgentConfigFileContent = AgentConfigLocator.extend({\n absolutePath: z.string(),\n exists: z.boolean(),\n content: z.string(),\n sha256: z.string().nullable(),\n});\nexport type AgentConfigFileContent = z.infer<typeof AgentConfigFileContent>;\n\n/**\n * `PUT /api/agent-config/file` (create or overwrite) and `POST /api/agent-config/file`\n * (create only, 409 `file_exists` if present). `expectedSha256` guards against overwriting\n * a file that changed since the editor loaded it (409 `file_changed`).\n */\nexport const AgentConfigWriteRequest = AgentConfigLocator.extend({\n content: z.string().max(2 * 1024 * 1024),\n expectedSha256: z.string().nullable().optional(),\n});\nexport type AgentConfigWriteRequest = z.infer<typeof AgentConfigWriteRequest>;\n\n/** Result of a write or delete; `backupPath` is the copy taken first (null for new files). */\nexport const AgentConfigWriteResponse = z.object({\n file: AgentConfigFileContent,\n backupPath: z.string().nullable(),\n});\nexport type AgentConfigWriteResponse = z.infer<typeof AgentConfigWriteResponse>;\n\n/** `DELETE /api/agent-config/file?root=&projectId=&path=` (`&folder=1` deletes a skill folder). */\nexport const AgentConfigDeleteQuery = AgentConfigLocator.extend({\n folder: z.enum([\"0\", \"1\"]).optional(),\n});\nexport type AgentConfigDeleteQuery = z.infer<typeof AgentConfigDeleteQuery>;\n\nexport const AgentConfigDeleteResponse = z.object({\n deleted: z.boolean(),\n backupPath: z.string().nullable(),\n});\nexport type AgentConfigDeleteResponse = z.infer<typeof AgentConfigDeleteResponse>;\n\n/** A unified diff preview of a proposed change. */\nexport const AgentConfigDiff = z.object({\n absolutePath: z.string(),\n exists: z.boolean(),\n patch: z.string(),\n additions: z.int().nonnegative(),\n deletions: z.int().nonnegative(),\n changed: z.boolean(),\n});\nexport type AgentConfigDiff = z.infer<typeof AgentConfigDiff>;\n\n/** `POST /api/agent-config/diff`: preview writing `content` (body: `AgentConfigWriteRequest`). */\nexport const AgentConfigDiffRequest = AgentConfigLocator.extend({\n content: z.string().max(2 * 1024 * 1024),\n});\nexport type AgentConfigDiffRequest = z.infer<typeof AgentConfigDiffRequest>;\n\n// ------------------------------------------------------------------------- MCP servers\n\n/** Where an MCP server is configured. */\nexport const McpConfigScope = z.enum([\"user\", \"local\", \"project\"]);\nexport type McpConfigScope = z.infer<typeof McpConfigScope>;\n\n/** A provider-neutral MCP server definition. Unknown native fields are kept in `extra`. */\nexport const McpServerSpec = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"stdio\"),\n command: z.string().min(1),\n args: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n cwd: z.string().optional(),\n enabled: z.boolean().optional(),\n extra: z.record(z.string(), z.unknown()).optional(),\n }),\n z.object({\n type: z.enum([\"http\", \"sse\"]),\n url: z.string().min(1),\n headers: z.record(z.string(), z.string()).optional(),\n /** Codex: name of the environment variable that holds a bearer token. */\n bearerTokenEnvVar: z.string().optional(),\n enabled: z.boolean().optional(),\n extra: z.record(z.string(), z.unknown()).optional(),\n }),\n]);\nexport type McpServerSpec = z.infer<typeof McpServerSpec>;\n\n/** One configured MCP server. `codeden` entries are CodeDen's own server (read-only). */\nexport const McpServerEntry = z.object({\n provider: z.enum([\"claude\", \"codex\", \"codeden\"]),\n scope: McpConfigScope,\n name: z.string(),\n spec: McpServerSpec,\n /** The native file it is defined in. */\n file: z.string(),\n /** Project the entry belongs to (`local` and `project` scopes). */\n projectId: Id.nullable(),\n});\nexport type McpServerEntry = z.infer<typeof McpServerEntry>;\n\n/** `GET /api/agent-config/mcp?projectId=`. */\nexport const McpServerListResponse = z.object({ servers: z.array(McpServerEntry) });\nexport type McpServerListResponse = z.infer<typeof McpServerListResponse>;\n\n/**\n * Target of an MCP edit. Claude: `user` (~/.claude.json), `local` (~/.claude.json, this\n * project) and `project` (`.mcp.json`). Codex: `user` (~/.codex/config.toml).\n */\nexport const McpServerTarget = z.object({\n provider: AgentConfigProvider,\n scope: McpConfigScope,\n projectId: Id.optional(),\n name: z\n .string()\n .min(1)\n .max(100)\n .regex(/^[A-Za-z0-9_.-]+$/),\n});\nexport type McpServerTarget = z.infer<typeof McpServerTarget>;\n\n/** `PUT /api/agent-config/mcp`: add or replace one server (other settings are kept). */\nexport const McpServerUpsertRequest = McpServerTarget.extend({ spec: McpServerSpec });\nexport type McpServerUpsertRequest = z.infer<typeof McpServerUpsertRequest>;\n\n/** `POST /api/agent-config/mcp/diff`: preview an upsert (with `spec`) or a removal (without). */\nexport const McpServerDiffRequest = McpServerTarget.extend({ spec: McpServerSpec.optional() });\nexport type McpServerDiffRequest = z.infer<typeof McpServerDiffRequest>;\n\n/** Result of an MCP upsert or delete. */\nexport const McpServerWriteResponse = z.object({\n file: z.string(),\n backupPath: z.string().nullable(),\n servers: z.array(McpServerEntry),\n});\nexport type McpServerWriteResponse = z.infer<typeof McpServerWriteResponse>;\n\n// The \"what's loaded\" view of a session is in `agent-config-loaded.ts`.\n","import { z } from \"zod\";\nimport { AgentConfigProvider, AgentConfigScope } from \"./agent-config\";\nimport { Id, Timestamp } from \"./common\";\n\n/**\n * Hooks (§12.4): commands a provider runs on lifecycle events (before or after a tool call, on\n * prompt submit, on stop, at session start, …). Claude Code keeps them in the `hooks` key of its\n * settings files: `~/.claude/settings.json` (user), `.claude/settings.json` (project, shared)\n * and `.claude/settings.local.json` (local). CodeDen edits only that key, in place, with a diff\n * preview and a backup. Only providers with `agentConfigFeatures[p].hooks` are listed.\n *\n * Native shape: `hooks: { [event]: [{ matcher?, hooks: [handler, …] }, …] }`.\n *\n * Claude Code has no per-hook switch, so \"disable\" takes the hook out of the file and keeps it\n * on CodeDen's shelf (`<codeden home>/agent-config/disabled-hooks.json`); \"enable\" writes it\n * back. The settings file always shows exactly what runs.\n *\n * Routes: `GET /api/agent-config/hooks?projectId=`, `POST /api/agent-config/hooks/diff` and\n * `POST /api/agent-config/hooks` (both take a `HookChangeRequest`).\n */\n\n/** Claude Code's documented hook events, most used first. Suggestions only: any name is kept. */\nexport const KNOWN_CLAUDE_HOOK_EVENTS = [\n \"PreToolUse\",\n \"PostToolUse\",\n \"PostToolUseFailure\",\n \"UserPromptSubmit\",\n \"Stop\",\n \"SubagentStop\",\n \"SessionStart\",\n \"SessionEnd\",\n \"Notification\",\n \"PermissionRequest\",\n \"PermissionDenied\",\n \"PreCompact\",\n \"PostCompact\",\n \"SubagentStart\",\n \"StopFailure\",\n \"PostToolBatch\",\n \"UserPromptExpansion\",\n \"MessageDisplay\",\n \"TaskCreated\",\n \"TaskCompleted\",\n \"TeammateIdle\",\n \"InstructionsLoaded\",\n \"ConfigChange\",\n \"CwdChanged\",\n \"FileChanged\",\n \"WorktreeCreate\",\n \"WorktreeRemove\",\n \"Elicitation\",\n \"ElicitationResult\",\n \"Setup\",\n] as const;\n\n/** A hook event name as written in a request (`PreToolUse`, …). */\nexport const HookEventName = z\n .string()\n .min(1)\n .max(64)\n .regex(/^[A-Za-z]+$/);\n\n/**\n * One hook handler, as stored natively. `type` is `command`, `http`, `mcp_tool`, `prompt`,\n * `agent` or a newer type. Every other native field (`if`, `statusMessage`, `async`, `headers`,\n * `allowedEnvVars`, …) is kept as is.\n */\nexport const HookHandler = z.looseObject({\n type: z.string().min(1).max(40),\n /** `command` hooks: the shell command. */\n command: z.string().optional(),\n /** `http` hooks: the URL the event is posted to. */\n url: z.string().optional(),\n /** `prompt` and `agent` hooks: the prompt. */\n prompt: z.string().optional(),\n /** Seconds before the hook is cancelled (the provider's default when absent). */\n timeout: z.number().optional(),\n});\nexport type HookHandler = z.infer<typeof HookHandler>;\n\n/** The field each editable hook type can't do without. */\nexport const HOOK_TYPE_MAIN_FIELD = {\n command: \"command\",\n http: \"url\",\n prompt: \"prompt\",\n agent: \"prompt\",\n} as const satisfies Record<string, \"command\" | \"url\" | \"prompt\">;\n\n/** A handler to write: its type's main field is set and the timeout is positive. */\nexport const HookHandlerInput = HookHandler.superRefine((h, ctx) => {\n const field = (HOOK_TYPE_MAIN_FIELD as Record<string, \"command\" | \"url\" | \"prompt\">)[h.type];\n if (field && !h[field]?.trim()) {\n ctx.addIssue({ code: \"custom\", path: [field], message: `A ${h.type} hook needs a ${field}` });\n }\n if (h.timeout !== undefined && !(h.timeout > 0)) {\n ctx.addIssue({ code: \"custom\", path: [\"timeout\"], message: \"The timeout must be positive\" });\n }\n});\n\n/** One settings file that holds hooks. */\nexport const HookSource = z.object({\n provider: AgentConfigProvider,\n scope: AgentConfigScope,\n /** Project the file belongs to (`project` and `local` scopes). */\n projectId: Id.nullable(),\n /** Absolute path of the settings file. */\n file: z.string(),\n exists: z.boolean(),\n /** The file sets `disableAllHooks: true`: none of its hooks run. */\n disableAllHooks: z.boolean(),\n /**\n * Set when the file can't be used: it doesn't parse, or it resolves (through a link) outside\n * its scope's folder. Its hooks are then not listed and it can't be written.\n */\n error: z.string().optional(),\n});\nexport type HookSource = z.infer<typeof HookSource>;\n\n/**\n * One hook handler. Active hooks are addressed by their position in `hooks[event]`\n * (`groupIndex`, `handlerIndex`); disabled ones live on CodeDen's shelf (`shelfId`).\n */\nexport const HookEntry = z.object({\n provider: AgentConfigProvider,\n scope: AgentConfigScope,\n projectId: Id.nullable(),\n /** The settings file it is (or, when disabled, was) defined in. */\n file: z.string(),\n event: z.string(),\n /**\n * Tool name or regex the group matches, exactly as written; null when the group has none or\n * an empty one (matches all).\n */\n matcher: z.string().nullable(),\n handler: HookHandler,\n /** False for a hook CodeDen took out of the file; it does not run. */\n enabled: z.boolean(),\n groupIndex: z.int().nonnegative().optional(),\n handlerIndex: z.int().nonnegative().optional(),\n shelfId: z.string().optional(),\n});\nexport type HookEntry = z.infer<typeof HookEntry>;\n\n/** `GET /api/agent-config/hooks?projectId=`: user hooks, plus the project's when given. */\nexport const HookListResponse = z.object({\n sources: z.array(HookSource),\n hooks: z.array(HookEntry),\n});\nexport type HookListResponse = z.infer<typeof HookListResponse>;\n\n/**\n * An active hook as listed: its file (provider, scope, project) and position, plus the handler\n * as it was read. A change is refused with 409 `hook_changed` if the handler there differs now.\n */\nexport const HookTarget = z.object({\n provider: AgentConfigProvider,\n scope: AgentConfigScope,\n projectId: Id.optional(),\n event: z.string().min(1).max(64),\n groupIndex: z.int().nonnegative(),\n handlerIndex: z.int().nonnegative(),\n expected: HookHandler,\n});\nexport type HookTarget = z.infer<typeof HookTarget>;\n\n/** A disabled hook on CodeDen's shelf. */\nexport const ShelvedHookRef = z.object({ shelfId: z.string().min(1).max(100) });\nexport type ShelvedHookRef = z.infer<typeof ShelvedHookRef>;\n\n/** Where a hook goes: event, optional matcher, handler. */\nconst HookPlacement = {\n event: HookEventName,\n /**\n * Tool name or regex, written exactly as given (whitespace can matter in a regex). Omitted or\n * empty: the group has no matcher (matches everything).\n */\n matcher: z.string().max(1_000).optional(),\n handler: HookHandlerInput,\n};\n\n/** Every change also says which list to return in `HookWriteResponse.hooks`. */\nconst HookListView = {\n /** The project whose hooks to list in the response (the page's selection); user only if absent. */\n listProjectId: Id.optional(),\n};\n\n/**\n * A change to one hook, previewed with `POST /api/agent-config/hooks/diff` (-> `AgentConfigDiff`)\n * and applied with `POST /api/agent-config/hooks` (-> `HookWriteResponse`):\n * - `add`: append to the first group in `event` with the same matcher, or a new group.\n * - `update`: replace in place, or move when the event or matcher changes.\n * - `remove`: delete from the file, or drop a disabled hook from the shelf.\n * - `disable`: take it out of the file onto CodeDen's shelf. `enable`: write it back.\n * Groups and events left empty are removed.\n */\nexport const HookChangeRequest = z.discriminatedUnion(\"action\", [\n z.object({\n action: z.literal(\"add\"),\n provider: AgentConfigProvider,\n scope: AgentConfigScope,\n projectId: Id.optional(),\n ...HookPlacement,\n ...HookListView,\n }),\n z.object({\n action: z.literal(\"update\"),\n target: HookTarget,\n ...HookPlacement,\n ...HookListView,\n }),\n z.object({\n action: z.literal(\"remove\"),\n target: z.union([HookTarget, ShelvedHookRef]),\n ...HookListView,\n }),\n z.object({ action: z.literal(\"disable\"), target: HookTarget, ...HookListView }),\n z.object({ action: z.literal(\"enable\"), target: ShelvedHookRef, ...HookListView }),\n]);\nexport type HookChangeRequest = z.infer<typeof HookChangeRequest>;\n\n/**\n * A hook taken out of its settings file by \"disable\", kept on CodeDen's shelf\n * (`<codeden home>/agent-config/disabled-hooks.json`, `{ \"hooks\": ShelvedHook[] }`) until it is\n * enabled (written back to the same scope) or removed.\n */\nexport const ShelvedHook = z.object({\n id: z.string().min(1).max(100),\n provider: AgentConfigProvider,\n scope: AgentConfigScope,\n projectId: Id.nullable(),\n /** The settings file it came from (shown in the list). */\n file: z.string(),\n event: z.string().min(1),\n matcher: z.string().nullable(),\n handler: HookHandler,\n disabledAt: Timestamp,\n});\nexport type ShelvedHook = z.infer<typeof ShelvedHook>;\n\n/** Result of a hook change; `backupPath` is the copy of the settings file taken first. */\nexport const HookWriteResponse = z.object({\n /** The settings file written, or null when only the shelf changed. */\n file: z.string().nullable(),\n backupPath: z.string().nullable(),\n /** The hooks after the change, for the request's `listProjectId`. */\n hooks: HookListResponse,\n});\nexport type HookWriteResponse = z.infer<typeof HookWriteResponse>;\n","import { z } from \"zod\";\nimport {\n AgentConfigFile,\n AgentConfigProvider,\n AgentConfigScope,\n McpServerEntry,\n} from \"./agent-config\";\nimport { HookEntry, HookSource } from \"./agent-config-hooks\";\nimport { Id } from \"./common\";\n\n/**\n * What's loaded (§12.4): for one session, the memory files, skills, subagents, MCP servers and\n * hooks its provider takes from its working directory. Computed from each provider's discovery\n * rules (not reported by the provider).\n */\n\n/** A skill folder (its `SKILL.md`). */\nexport const AgentSkill = z.object({\n provider: AgentConfigProvider,\n scope: AgentConfigScope,\n name: z.string(),\n description: z.string().optional(),\n file: AgentConfigFile,\n});\nexport type AgentSkill = z.infer<typeof AgentSkill>;\n\n/**\n * The hooks that apply to a session's working folder. For Claude Code: `~/.claude/settings.json`,\n * the working folder's own `.claude/settings.json` (no parent fallback), and\n * `.claude/settings.local.json` at the repository root (the main checkout's root for a\n * worktree), or beside the shared file on Windows and outside a git repository.\n */\nexport const LoadedHooks = z.object({\n /** The settings files that apply, lowest precedence first (user, project, local). */\n sources: z.array(HookSource),\n /** The hooks those files define, in the same order. Hooks on CodeDen's shelf don't run and aren't listed. */\n hooks: z.array(HookEntry),\n /**\n * The settings file whose `disableAllHooks: true` wins after precedence (local over project\n * over user), so none of the listed hooks run; null when hooks are on.\n */\n disabledBy: z.string().nullable(),\n});\nexport type LoadedHooks = z.infer<typeof LoadedHooks>;\n\n/**\n * `GET /api/sessions/:id/agent-config/loaded`: what the session's provider loads into its\n * context from its working directory, in load order.\n */\nexport const LoadedAgentConfig = z.object({\n sessionId: Id,\n provider: z.string(),\n cwd: z.string(),\n /** Memory, rule and auto-memory files that exist, broadest scope first. */\n memory: z.array(AgentConfigFile),\n skills: z.array(AgentSkill),\n subagents: z.array(AgentConfigFile),\n /** Enabled MCP servers, including CodeDen's own. */\n mcpServers: z.array(McpServerEntry),\n /** Hooks from the provider's settings files; null when its native config has no hooks. */\n hooks: LoadedHooks.nullable(),\n});\nexport type LoadedAgentConfig = z.infer<typeof LoadedAgentConfig>;\n","import { z } from \"zod\";\nimport { McpServerSpec, McpServerTarget } from \"./agent-config\";\n\n/**\n * Connection test of one MCP server (§12.4): the runner connects to it as an agent would,\n * runs the MCP `initialize` handshake and `tools/list`, then stops it.\n */\n\n/** Most tools listed in a test result (`toolCount` is the full number). */\nexport const MCP_TEST_MAX_TOOLS = 500;\n/** Most `tools/list` pages a test follows; beyond them `morePages` is set. */\nexport const MCP_TEST_MAX_PAGES = 100;\n/** Most characters of a tool description kept in a test result. */\nexport const MCP_TEST_DESCRIPTION_LIMIT = 300;\n/** Most characters of the error message of a failed test. */\nexport const MCP_TEST_ERROR_LIMIT = 2000;\n/** Most characters of a stdio server's stderr kept in a failed test (its end). */\nexport const MCP_TEST_STDERR_LIMIT = 4000;\n/** Default time a test may take, including a first-run `npx` download. */\nexport const MCP_TEST_DEFAULT_TIMEOUT_MS = 60_000;\n/** Longest timeout a test may ask for. */\nexport const MCP_TEST_MAX_TIMEOUT_MS = 120_000;\n\n/**\n * `POST /api/agent-config/mcp/test`. With `spec`, those (unsaved) values are tested, as from\n * the add/edit dialog; without it, the server saved at the target is.\n */\nexport const McpServerTestRequest = McpServerTarget.extend({ spec: McpServerSpec.optional() });\nexport type McpServerTestRequest = z.infer<typeof McpServerTestRequest>;\n\n/**\n * How a connection test builds a stdio server's environment, the way the agent's CLI does:\n * - `inherit` (Claude Code): the runner's environment, minus CodeDen's own secrets, plus the\n * server's `env`.\n * - `allowlist` (Codex): only the platform's default variables (PATH, HOME or USERPROFILE, the\n * temp folder and the like) and CA bundle variables, the names in the server's native\n * `env_vars` list (kept in the spec's `extra`), then the server's `env`.\n */\nexport const McpStdioEnv = z.enum([\"inherit\", \"allowlist\"]);\nexport type McpStdioEnv = z.infer<typeof McpStdioEnv>;\n\n/** One tool a server offers. */\nexport const McpTestTool = z.object({\n name: z.string(),\n title: z.string().optional(),\n /** Cut to `MCP_TEST_DESCRIPTION_LIMIT` characters. */\n description: z.string().max(MCP_TEST_DESCRIPTION_LIMIT).optional(),\n});\nexport type McpTestTool = z.infer<typeof McpTestTool>;\n\n/** Where a failed test stopped: starting the server, the handshake, or listing its tools. */\nexport const McpTestStage = z.enum([\"start\", \"connect\", \"list_tools\"]);\nexport type McpTestStage = z.infer<typeof McpTestStage>;\n\n/**\n * Result of a connection test (the `mcp.test` runner command and the HTTP route). A server\n * that fails is a result with `ok: false`, never a request error.\n */\nexport const McpServerTestResult = z.discriminatedUnion(\"ok\", [\n z.object({\n ok: z.literal(true),\n /** Wall time from start to the end of `tools/list`. */\n durationMs: z.int().nonnegative(),\n /** What the server reported in `initialize`. */\n server: z.object({ name: z.string(), version: z.string(), title: z.string().optional() }),\n /** The protocol version both sides agreed on, when known. */\n protocolVersion: z.string().nullable(),\n /**\n * The tools on the pages read: every tool the server offers (0 when it has no tools\n * capability), unless `morePages` is set.\n */\n toolCount: z.int().nonnegative(),\n /**\n * The server still had pages after `MCP_TEST_MAX_PAGES`, which the test didn't read:\n * `toolCount` is then a lower bound (\"more than N tools\").\n */\n morePages: z.boolean(),\n /** The first `MCP_TEST_MAX_TOOLS` of them. */\n tools: z.array(McpTestTool).max(MCP_TEST_MAX_TOOLS),\n }),\n z.object({\n ok: z.literal(false),\n durationMs: z.int().nonnegative(),\n stage: McpTestStage,\n /** Why it failed, cut to `MCP_TEST_ERROR_LIMIT` characters. */\n error: z.string().max(MCP_TEST_ERROR_LIMIT),\n /** The test ran out of time (the server was stopped). */\n timedOut: z.boolean(),\n /** The end of a stdio server's stderr, when it wrote any. */\n stderrTail: z.string().max(MCP_TEST_STDERR_LIMIT).optional(),\n /**\n * What may explain the failure beyond the error itself, such as the provider giving a\n * stdio server only some of the environment (`McpStdioEnv` `allowlist`).\n */\n note: z.string().max(MCP_TEST_ERROR_LIMIT).optional(),\n }),\n]);\nexport type McpServerTestResult = z.infer<typeof McpServerTestResult>;\n","import { z } from \"zod\";\nimport { Id } from \"./common\";\n\n/** Where the bytes of an attachment come from. */\nexport const AttachmentSource = z.discriminatedUnion(\"type\", [\n /** Inline base64 data (pasted images). */\n z.object({ type: z.literal(\"base64\"), data: z.base64() }),\n /** A file on the runner's filesystem. */\n z.object({ type: z.literal(\"path\"), path: z.string().min(1) }),\n /** A stored CodeDen artifact (§6 `artifacts/`). */\n z.object({ type: z.literal(\"artifact\"), artifactId: Id }),\n]);\nexport type AttachmentSource = z.infer<typeof AttachmentSource>;\n\n/** Image MIME types accepted as agent input. */\nexport const ImageMediaType = z.enum([\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"]);\nexport type ImageMediaType = z.infer<typeof ImageMediaType>;\n\n/** An attachment on a user message: an image, or a file reference. */\nexport const Attachment = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"image\"),\n mediaType: ImageMediaType,\n source: AttachmentSource,\n name: z.string().optional(),\n }),\n z.object({\n type: z.literal(\"file\"),\n /** Path on the runner, usually inside the session worktree. */\n path: z.string().min(1),\n name: z.string().optional(),\n mediaType: z.string().optional(),\n }),\n]);\nexport type Attachment = z.infer<typeof Attachment>;\n\n/**\n * Who sent a message to a session: the user, the orchestrator (to a PM), a PM (to its\n * sessions), the software factory's loop (its briefs, fix rounds and nudges), an automation,\n * or CodeDen itself (automatic wake-ups, retries, pull request feedback).\n */\nexport const MessageSender = z.enum([\n \"user\",\n \"orchestrator\",\n \"pm\",\n \"factory\",\n \"automation\",\n \"codeden\",\n]);\nexport type MessageSender = z.infer<typeof MessageSender>;\n\n/** Input that starts or steers a turn: text plus optional image/file attachments. */\nexport const UserInput = z.object({\n text: z.string(),\n attachments: z.array(Attachment).default([]),\n /**\n * Who wrote the message, when it was not the user: recorded so the transcript can show the\n * sender without reading the text, a session's opening brief included. Absent on the user's\n * own messages and on every message stored before senders were recorded.\n */\n from: MessageSender.optional(),\n});\nexport type UserInput = z.infer<typeof UserInput>;\n/** Input shape accepted before defaults are applied (`attachments` optional). */\nexport type UserInputInit = z.input<typeof UserInput>;\n\n/** Senders whose messages are introduced to the agent with a line that names them. */\nexport type RoleSender = \"pm\" | \"orchestrator\";\n\n/**\n * The first line of a message from a PM or the orchestrator, telling the agent who wrote it.\n * The only definition of these words: the server writes them, the UI recognises them.\n */\nexport const SENDER_LINES: Readonly<Record<RoleSender, string>> = {\n pm: \"Message from your project manager:\",\n orchestrator: \"Message from the orchestrator:\",\n};\n\n/**\n * Input for a message from a PM or the orchestrator: the sender is recorded in `from` and\n * named for the agent in the text's first line (`SENDER_LINES`).\n */\nexport function messageFrom(from: RoleSender, text: string): UserInput {\n return { text: `${SENDER_LINES[from]}\\n${text}`, attachments: [], from };\n}\n\n/**\n * Who wrote a message, and its text without the sender line `messageFrom` added. A recorded\n * `from` wins. Without one (messages stored before senders were recorded, providers that echo\n * only the text back) a leading sender line identifies a PM or the orchestrator; anything else\n * is the user's.\n */\nexport function splitSender(\n text: string,\n from?: MessageSender,\n): { from: MessageSender; text: string } {\n for (const sender of [\"pm\", \"orchestrator\"] as const) {\n if (from !== undefined && from !== sender) continue;\n const line = SENDER_LINES[sender];\n const rest = text.slice(line.length);\n if (text.startsWith(line) && (rest === \"\" || /^\\r?\\n/.test(rest))) {\n return { from: sender, text: rest.replace(/^\\r?\\n/, \"\") };\n }\n }\n return { from: from ?? \"user\", text };\n}\n","import { z } from \"zod\";\nimport { ErrorInfo, Id, JsonValue } from \"./common\";\nimport { UserInput } from \"./input\";\n\n/**\n * Lifecycle status of an item. For `approval_request` and `user_question`,\n * `in_progress` means \"waiting on a response\".\n */\nexport const ItemStatus = z.enum([\"in_progress\", \"completed\", \"failed\", \"declined\", \"cancelled\"]);\nexport type ItemStatus = z.infer<typeof ItemStatus>;\n\nconst itemBase = {\n /** Unique within the session. */\n id: Id,\n status: ItemStatus,\n};\n\n/** A message the user (or a PM/orchestrator acting as the user) sent. */\nexport const UserMessageItem = z.object({\n ...itemBase,\n kind: z.literal(\"user_message\"),\n input: UserInput,\n});\n\n/** Assistant text (markdown). Streamed via `item.delta` `{ type: \"text\" }`. */\nexport const AssistantMessageItem = z.object({\n ...itemBase,\n kind: z.literal(\"assistant_message\"),\n text: z.string(),\n});\n\n/** Model reasoning, when the provider exposes it. */\nexport const ReasoningItem = z.object({\n ...itemBase,\n kind: z.literal(\"reasoning\"),\n text: z.string(),\n summary: z.string().optional(),\n /** True when the provider hides the content and only reports that reasoning happened. */\n redacted: z.boolean().optional(),\n});\n\n/** Preview of a tool's output. Large outputs are truncated and fetched on demand (§6). */\nexport const ToolOutput = z.object({\n text: z.string(),\n truncated: z.boolean().default(false),\n totalBytes: z.int().nonnegative().optional(),\n /** Artifact holding the full output when truncated. */\n artifactId: Id.optional(),\n});\nexport type ToolOutput = z.infer<typeof ToolOutput>;\n\n/** What kind of work a tool call performs; drives rendering, never provider-specific. */\nexport const ToolKind = z.enum([\n \"command\",\n \"file_edit\",\n \"file_read\",\n \"search\",\n \"web\",\n \"mcp\",\n \"browser\",\n \"other\",\n]);\nexport type ToolKind = z.infer<typeof ToolKind>;\n\n/**\n * An image file a tool call created on this machine, e.g. with a provider's built-in image\n * generation. Items point at the file and never carry the image bytes: the server copies it\n * into the session's artifacts and shows it inline in the transcript, once per item.\n */\nexport const GeneratedImage = z.object({\n /** Absolute path of the image file. */\n path: z.string().min(1),\n /** Shown with the image, e.g. the prompt it was generated from. */\n caption: z.string().optional(),\n});\nexport type GeneratedImage = z.infer<typeof GeneratedImage>;\n\nconst toolCallBase = {\n ...itemBase,\n kind: z.literal(\"tool_call\"),\n /** Provider-native tool name, e.g. `Bash`, `apply_patch`, `mcp__codeden__finish`. */\n toolName: z.string(),\n /** Short human title, e.g. `Run pnpm test`. */\n title: z.string().optional(),\n /** Raw tool input as JSON. */\n input: JsonValue.optional(),\n output: ToolOutput.optional(),\n error: ErrorInfo.optional(),\n durationMs: z.int().nonnegative().optional(),\n /** Images the call created, by file path (see {@link GeneratedImage}). */\n generatedImages: z.array(GeneratedImage).optional(),\n};\n\n/** A single file change produced by a `file_edit` tool call. */\nexport const FileChange = z.object({\n path: z.string(),\n change: z.enum([\"add\", \"modify\", \"delete\", \"rename\"]),\n previousPath: z.string().optional(),\n /** Unified diff, when available. */\n diff: z.string().optional(),\n additions: z.int().nonnegative().optional(),\n deletions: z.int().nonnegative().optional(),\n});\nexport type FileChange = z.infer<typeof FileChange>;\n\n/** Tool call item; a nested discriminated union on `toolKind`. */\nexport const ToolCallItem = z.discriminatedUnion(\"toolKind\", [\n z.object({\n ...toolCallBase,\n toolKind: z.literal(\"command\"),\n command: z.string(),\n cwd: z.string().optional(),\n exitCode: z.int().nullable().optional(),\n }),\n z.object({\n ...toolCallBase,\n toolKind: z.literal(\"file_edit\"),\n changes: z.array(FileChange),\n }),\n z.object({\n ...toolCallBase,\n toolKind: z.literal(\"file_read\"),\n path: z.string(),\n startLine: z.int().positive().optional(),\n endLine: z.int().positive().optional(),\n }),\n z.object({\n ...toolCallBase,\n toolKind: z.literal(\"search\"),\n query: z.string(),\n path: z.string().optional(),\n matchCount: z.int().nonnegative().optional(),\n }),\n z.object({\n ...toolCallBase,\n toolKind: z.literal(\"web\"),\n url: z.string().optional(),\n query: z.string().optional(),\n }),\n z.object({\n ...toolCallBase,\n toolKind: z.literal(\"mcp\"),\n server: z.string(),\n tool: z.string(),\n }),\n z.object({\n ...toolCallBase,\n toolKind: z.literal(\"browser\"),\n action: z.string(),\n url: z.string().optional(),\n }),\n z.object({ ...toolCallBase, toolKind: z.literal(\"other\") }),\n]);\nexport type ToolCallItem = z.infer<typeof ToolCallItem>;\n\n/** A proposed plan (markdown), e.g. from plan mode. */\nexport const PlanItem = z.object({\n ...itemBase,\n kind: z.literal(\"plan\"),\n text: z.string(),\n});\n\nexport const TodoStatus = z.enum([\"pending\", \"in_progress\", \"completed\"]);\nexport type TodoStatus = z.infer<typeof TodoStatus>;\n\n/** The agent's working todo list. Updated in place via `item.updated`. */\nexport const TodoListItem = z.object({\n ...itemBase,\n kind: z.literal(\"todo_list\"),\n todos: z.array(\n z.object({\n id: z.string().optional(),\n text: z.string(),\n status: TodoStatus,\n }),\n ),\n});\n\n/** Decisions a user (or policy) can make on an approval request. */\nexport const ApprovalDecision = z.enum([\"allow_once\", \"allow_session\", \"deny\"]);\nexport type ApprovalDecision = z.infer<typeof ApprovalDecision>;\n\n/**\n * Who decided an approval: the user, CodeDen's policy (an action the permission level allows,\n * or a denial in a session nobody is watching), or a PM.\n */\nexport const ApprovalDecider = z.enum([\"user\", \"policy\", \"pm\"]);\nexport type ApprovalDecider = z.infer<typeof ApprovalDecider>;\n\n/**\n * What an approval request is about. `plan`: the agent finished planning (plan mode) and asks\n * to start implementing; approving continues at the session's permission level, denying keeps\n * it planning with the user's `message` as feedback.\n */\nexport const ApprovalAction = z.enum([\n \"command\",\n \"file_change\",\n \"outside_worktree\",\n \"network\",\n \"git_destructive\",\n \"secrets\",\n \"tool\",\n \"plan\",\n \"other\",\n]);\nexport type ApprovalAction = z.infer<typeof ApprovalAction>;\n\n/**\n * An approval the agent is waiting on (§11.2). Surfaces in the transcript, the parent thread\n * (for subagents) and the inbox. Answered with `RuntimeResponse { kind: \"approval\" }`.\n */\nexport const ApprovalRequestItem = z.object({\n ...itemBase,\n kind: z.literal(\"approval_request\"),\n /** Id passed back to `ProviderSession.respond`. */\n requestId: Id,\n action: ApprovalAction,\n title: z.string(),\n /** Why this was flagged as risky. */\n reason: z.string().optional(),\n command: z.string().optional(),\n cwd: z.string().optional(),\n paths: z.array(z.string()).optional(),\n toolName: z.string().optional(),\n toolInput: JsonValue.optional(),\n /** The tool call item this approval gates, if any. */\n toolCallItemId: Id.optional(),\n options: z.array(ApprovalDecision).default([\"allow_once\", \"allow_session\", \"deny\"]),\n decision: ApprovalDecision.optional(),\n decidedBy: ApprovalDecider.optional(),\n});\n\n/** One question in a `user_question` item. */\nexport const UserQuestion = z.object({\n id: Id,\n /** Short label (a few words) shown as a chip/header. */\n header: z.string().optional(),\n question: z.string(),\n options: z.array(z.object({ label: z.string(), description: z.string().optional() })).default([]),\n multiSelect: z.boolean().default(false),\n allowFreeText: z.boolean().default(true),\n});\nexport type UserQuestion = z.infer<typeof UserQuestion>;\n\n/** Questions the agent asks the user. Answered with `RuntimeResponse { kind: \"answer\" }`. */\nexport const UserQuestionItem = z.object({\n ...itemBase,\n kind: z.literal(\"user_question\"),\n requestId: Id,\n questions: z.array(UserQuestion).min(1),\n /** Answers keyed by question id, once answered. */\n answers: z.record(z.string(), z.array(z.string())).optional(),\n /**\n * Who answered: the user, or the project manager of the session's project (its\n * `answer_question` tool, §8.2 step 5). Absent on questions answered before it was recorded.\n */\n decidedBy: z.enum([\"user\", \"pm\"]).optional(),\n /**\n * Asked through CodeDen's `ask_user` tool rather than the provider: stays open after its\n * turn ends, and an answer that arrives after the tool returned is sent as a new message.\n */\n deferred: z.boolean().optional(),\n});\n\n/**\n * What a finished subagent used, as its provider reports it (§7.3). Each figure is optional:\n * a provider that reports none leaves `SubagentItem.stats` out. Display only: never added to\n * usage totals (`usage.updated`), which come from the provider's own turn figures.\n */\nexport const SubagentStats = z.object({\n /** Tokens the subagent used in total (input, output and cache). */\n totalTokens: z.int().nonnegative().optional(),\n /** Tool calls the subagent made. */\n toolUses: z.int().nonnegative().optional(),\n /** How long the subagent ran, in milliseconds. */\n durationMs: z.int().nonnegative().optional(),\n});\nexport type SubagentStats = z.infer<typeof SubagentStats>;\n\n/** A subagent run; its transcript lives in the child thread `childThreadId` (§7.3). */\nexport const SubagentItem = z.object({\n ...itemBase,\n kind: z.literal(\"subagent\"),\n childThreadId: Id,\n /** Subagent type/name, e.g. `code-reviewer`. */\n agentType: z.string().optional(),\n description: z.string().optional(),\n prompt: z.string().optional(),\n /** Final result summary when completed. */\n summary: z.string().optional(),\n /** Tokens, tool calls and duration of the finished run, when the provider reports them. */\n stats: SubagentStats.optional(),\n});\n\n/** One suggested next prompt (§7.5). */\nexport const FollowupSuggestion = z.object({\n prompt: z.string().min(1),\n /** Short chip label; the UI falls back to a truncated prompt. */\n label: z.string().optional(),\n});\nexport type FollowupSuggestion = z.infer<typeof FollowupSuggestion>;\n\n/** Suggested follow-up prompts, stored on the turn and shown as chips (§7.5). */\nexport const FollowupsItem = z.object({\n ...itemBase,\n kind: z.literal(\"followups\"),\n /** `agent`: via the `suggest_followups` tool; `utility`: fallback from the utility model. */\n source: z.enum([\"agent\", \"utility\"]),\n suggestions: z.array(FollowupSuggestion).min(1).max(4),\n});\n\n/** Informational notice inside a transcript (e.g. \"context compacted\"). */\nexport const NoticeItem = z.object({\n ...itemBase,\n kind: z.literal(\"notice\"),\n level: z.enum([\"info\", \"warning\"]),\n code: z.string().optional(),\n message: z.string(),\n data: JsonValue.optional(),\n});\n\n/** An error shown inline in the transcript (the turn may still continue). */\nexport const ErrorItem = z.object({\n ...itemBase,\n kind: z.literal(\"error\"),\n error: ErrorInfo,\n});\n\n/** Every item kind in a turn (§7.3). Discriminated on `kind` (tool calls also on `toolKind`). */\nexport const Item = z.discriminatedUnion(\"kind\", [\n UserMessageItem,\n AssistantMessageItem,\n ReasoningItem,\n ToolCallItem,\n PlanItem,\n TodoListItem,\n ApprovalRequestItem,\n UserQuestionItem,\n SubagentItem,\n FollowupsItem,\n NoticeItem,\n ErrorItem,\n]);\nexport type Item = z.infer<typeof Item>;\nexport type ItemKind = Item[\"kind\"];\n/** Narrow `Item` to one kind: `ItemOf<\"subagent\">`. */\nexport type ItemOf<K extends ItemKind> = Extract<Item, { kind: K }>;\n\n/** Incremental update to an in-progress item, carried by `item.delta`. */\nexport const ItemDelta = z.discriminatedUnion(\"type\", [\n /** Append to `text` of assistant_message / reasoning / plan. */\n z.object({ type: z.literal(\"text\"), text: z.string() }),\n /** Append to a reasoning item's `summary`. */\n z.object({ type: z.literal(\"reasoning_summary\"), text: z.string() }),\n /** Append to a tool call's `output.text` (live command output). */\n z.object({\n type: z.literal(\"tool_output\"),\n text: z.string(),\n stream: z.enum([\"stdout\", \"stderr\"]).optional(),\n }),\n /** Streaming tool input JSON fragment (display only). */\n z.object({ type: z.literal(\"tool_input\"), partialJson: z.string() }),\n]);\nexport type ItemDelta = z.infer<typeof ItemDelta>;\n","import { z } from \"zod\";\nimport { ProviderId } from \"./common\";\n\n/**\n * `/` commands and skills offered by the composer (§13). The server lists them per session from\n * the skills and custom commands that apply to its working folder, plus whatever the provider\n * itself reports (its built-in commands, plugin commands).\n */\n\n/** Longest description kept for a `/` entry; the composer shows one line. */\nexport const SLASH_DESCRIPTION_MAX = 200;\n\n/** The first line of `text`, cut to `max` characters (with an ellipsis when cut). */\nexport function oneLineDescription(text: string, max = SLASH_DESCRIPTION_MAX): string {\n const line = text.trim().split(/\\r?\\n/, 1)[0]?.trim() ?? \"\";\n return line.length > max ? `${line.slice(0, max - 1).trimEnd()}…` : line;\n}\n\n/**\n * One command as a provider reports it for a live session (`session.updated.commands`):\n * built-in commands and everything else it would run for `/<name>`.\n */\nexport const ProviderCommand = z.object({\n /** Name without the leading slash, e.g. `compact`. */\n name: z.string().min(1),\n /** One line about what it does; empty when the provider gives none. */\n description: z.string(),\n /** Hint for the arguments it takes, e.g. `<file>`. */\n argumentHint: z.string().optional(),\n /** True for the provider's own commands (absent for user, project and plugin ones). */\n builtin: z.boolean().optional(),\n});\nexport type ProviderCommand = z.infer<typeof ProviderCommand>;\n\n/**\n * One command per name, the one `/<name>` runs: a built-in row wins over other rows of its\n * name (user, project, plugin), otherwise the first row does. Keeps first-appearance order.\n */\nexport function winningCommands<T extends { name: string; builtin?: boolean }>(\n commands: readonly T[],\n): T[] {\n const byName = new Map<string, T>();\n for (const c of commands) {\n const kept = byName.get(c.name);\n if (!kept || (c.builtin === true && kept.builtin !== true)) byName.set(c.name, c);\n }\n return [...byName.values()];\n}\n\n/** A command the agent runs, or a skill it loads. */\nexport const SlashCommandKind = z.enum([\"command\", \"skill\"]);\nexport type SlashCommandKind = z.infer<typeof SlashCommandKind>;\n\n/** One entry of the composer's `/` menu. Picking it inserts `/<name> `. */\nexport const SlashCommand = z.object({\n /** Name without the leading slash, as typed after `/`. */\n name: z.string().min(1),\n /** One line about what it does; empty when there is none. */\n description: z.string(),\n kind: SlashCommandKind,\n /** The provider whose configuration defines it. */\n provider: ProviderId.optional(),\n /** Hint for the arguments it takes, e.g. `[issue-number]`. */\n argumentHint: z.string().optional(),\n});\nexport type SlashCommand = z.infer<typeof SlashCommand>;\n\n/** `GET /api/sessions/:id/commands`: the session's commands and skills, sorted by name. */\nexport const SlashCommandList = z.array(SlashCommand);\nexport type SlashCommandList = z.infer<typeof SlashCommandList>;\n","import { z } from \"zod\";\nimport { ErrorInfo, Id } from \"./common\";\nimport { Item, ItemDelta } from \"./items\";\nimport { ProviderCommand } from \"./slash-commands\";\n\n/**\n * Token/cost/rate-limit usage. Providers fill in what they report; everything is optional.\n * With a `turnId`, token counts and cost are that turn's own usage so far (never a running\n * session total). `inputTokens` excludes cache reads and writes; `reasoningTokens` is\n * already included in `outputTokens`.\n */\nexport const Usage = z.object({\n inputTokens: z.int().nonnegative().optional(),\n outputTokens: z.int().nonnegative().optional(),\n cachedInputTokens: z.int().nonnegative().optional(),\n cacheWriteTokens: z.int().nonnegative().optional(),\n reasoningTokens: z.int().nonnegative().optional(),\n /** Tokens currently occupying the context window. */\n contextTokens: z.int().nonnegative().optional(),\n contextWindow: z.int().positive().optional(),\n /** Cost in USD where the provider reports it. */\n costUsd: z.number().nonnegative().optional(),\n rateLimits: z\n .array(\n z.object({\n /** Window name, e.g. `5h`, `weekly`. */\n id: z.string(),\n status: z.enum([\"ok\", \"warning\", \"limited\"]),\n usedPercent: z.number().min(0).max(100).optional(),\n resetsAt: z.iso.datetime().optional(),\n }),\n )\n .optional(),\n});\nexport type Usage = z.infer<typeof Usage>;\n\n/** A conversation thread. Root threads have no parent; subagent threads link to their spawner. */\nexport const ThreadInfo = z.object({\n id: Id,\n parentThreadId: Id.optional(),\n /** The `subagent` item in the parent thread that spawned this thread. */\n parentItemId: Id.optional(),\n title: z.string().optional(),\n agentType: z.string().optional(),\n});\nexport type ThreadInfo = z.infer<typeof ThreadInfo>;\n\nconst threadScoped = { threadId: Id };\nconst turnScoped = { threadId: Id, turnId: Id };\n\n/** Session-level metadata changed (resume token assigned, model switched, title generated). */\nexport const SessionUpdatedEvent = z.object({\n type: z.literal(\"session.updated\"),\n resumeToken: z.string().optional(),\n model: z.string().optional(),\n title: z.string().optional(),\n /** The agent entered or left plan mode on its own, e.g. it left once its plan was approved. */\n planMode: z.boolean().optional(),\n /**\n * The full list of `/` commands the provider reports for this session (built-in, plugin,\n * custom). Replaces any earlier list; absent when unchanged or not reported.\n */\n commands: z.array(ProviderCommand).optional(),\n});\n\n/** A thread came into existence. Emitted for the root thread and every subagent thread. */\nexport const ThreadStartedEvent = z.object({\n type: z.literal(\"thread.started\"),\n thread: ThreadInfo,\n});\n\nexport const TurnStartedEvent = z.object({ type: z.literal(\"turn.started\"), ...turnScoped });\n\nexport const TurnCompletedEvent = z.object({\n type: z.literal(\"turn.completed\"),\n ...turnScoped,\n /** Provider stop reason, e.g. `end_turn`, `max_tokens`. */\n stopReason: z.string().optional(),\n});\n\nexport const TurnFailedEvent = z.object({\n type: z.literal(\"turn.failed\"),\n ...turnScoped,\n error: ErrorInfo,\n});\n\nexport const TurnInterruptedEvent = z.object({\n type: z.literal(\"turn.interrupted\"),\n ...turnScoped,\n /** `user`: interrupt button; `runner_restart`: cut off by a runner drain/crash; `provider`: provider-side. */\n reason: z.enum([\"user\", \"runner_restart\", \"provider\"]),\n});\n\n/** A new item appeared in a turn (possibly still in progress). */\nexport const ItemStartedEvent = z.object({\n type: z.literal(\"item.started\"),\n ...turnScoped,\n item: Item,\n});\n\n/** Incremental content for an in-progress item. */\nexport const ItemDeltaEvent = z.object({\n type: z.literal(\"item.delta\"),\n ...turnScoped,\n itemId: Id,\n delta: ItemDelta,\n});\n\n/** Full replacement of an item's state while it is still in progress (todo list edits, etc.). */\nexport const ItemUpdatedEvent = z.object({\n type: z.literal(\"item.updated\"),\n ...turnScoped,\n item: Item,\n});\n\n/** Final state of an item. Authoritative: replaces anything accumulated from deltas. */\nexport const ItemCompletedEvent = z.object({\n type: z.literal(\"item.completed\"),\n ...turnScoped,\n item: Item,\n});\n\nexport const UsageUpdatedEvent = z.object({\n type: z.literal(\"usage.updated\"),\n ...threadScoped,\n turnId: Id.optional(),\n usage: Usage,\n});\n\n/**\n * Normalized agent event (§7.3). Every provider adapter emits exactly this stream;\n * the UI and orchestration never see provider-native shapes.\n */\nexport const AgentEvent = z.discriminatedUnion(\"type\", [\n SessionUpdatedEvent,\n ThreadStartedEvent,\n TurnStartedEvent,\n TurnCompletedEvent,\n TurnFailedEvent,\n TurnInterruptedEvent,\n ItemStartedEvent,\n ItemDeltaEvent,\n ItemUpdatedEvent,\n ItemCompletedEvent,\n UsageUpdatedEvent,\n]);\nexport type AgentEvent = z.infer<typeof AgentEvent>;\nexport type AgentEventType = AgentEvent[\"type\"];\n/** Narrow `AgentEvent` by type: `AgentEventOf<\"item.delta\">`. */\nexport type AgentEventOf<T extends AgentEventType> = Extract<AgentEvent, { type: T }>;\n\n/** All agent event type names, useful for filters. */\nexport const AGENT_EVENT_TYPES = AgentEvent.options.map(\n (o) => o.shape.type.value,\n) as readonly AgentEventType[];\n","import { z } from \"zod\";\nimport { GitHubIssueRef, GitHubPrRef, Id, JsonValue, Timestamp } from \"../common\";\n\n/** What an inbox item asks of the user (§11.1). */\nexport const InboxItemKind = z.enum([\n \"question\",\n \"approval\",\n \"pr_review\",\n \"run_failed\",\n \"triage\",\n \"automation_result\",\n \"message\",\n /** A start request that matched running work (§8.4); resolved with wait/skip/join/force. */\n \"conflict\",\n /**\n * A session's worktree could not be removed (§9), for example because a program outside\n * CodeDen still uses it. Resolved by CodeDen once a later attempt removes it.\n */\n \"cleanup_failed\",\n]);\nexport type InboxItemKind = z.infer<typeof InboxItemKind>;\n\nexport const InboxItemStatus = z.enum([\"open\", \"resolved\", \"dismissed\"]);\nexport type InboxItemStatus = z.infer<typeof InboxItemStatus>;\n\n/**\n * Who an inbox item is for, set by the server when it raises the item (§11.1). Settings →\n * Notifications chooses which categories raise a toast and a desktop notification; every item\n * lands in the inbox either way.\n * - `needs_you`: the user should act: approvals and questions, a PR only a person merges, a\n * factory decision flagged `needsHuman`, a start conflict, a budget alert.\n * - `failure`: something broke and needs a person: a failed run of a session the factory doesn't\n * look after, a paused factory loop, a regression, a worktree that couldn't be removed.\n * - `factory`: the factory's own activity, which it handles itself: its decisions, PRs it\n * reviews and merges, its sessions' failures, stopped items, the daily digest.\n * - `automation`: automation results and triage decisions.\n */\nexport const InboxNotify = z.enum([\"needs_you\", \"failure\", \"factory\", \"automation\"]);\nexport type InboxNotify = z.infer<typeof InboxNotify>;\n\n/** One thing waiting on the user. Links to its session, issue and PR and is answerable in place. */\nexport const InboxItem = z.object({\n id: Id,\n kind: InboxItemKind,\n status: InboxItemStatus,\n priority: z.enum([\"low\", \"normal\", \"high\"]).default(\"normal\"),\n /** Which notification category it raises (items stored before it existed read as `needs_you`). */\n notify: InboxNotify.default(\"needs_you\"),\n title: z.string(),\n body: z.string().nullable(),\n projectId: Id.nullable(),\n sessionId: Id.nullable(),\n threadId: Id.nullable(),\n /** The transcript item (approval_request / user_question) this mirrors. */\n itemId: Id.nullable(),\n /** Provider request id to answer, for approvals and questions. */\n requestId: Id.nullable(),\n issue: GitHubIssueRef.nullable(),\n pr: GitHubPrRef.nullable(),\n automationRunId: Id.nullable(),\n createdAt: Timestamp,\n updatedAt: Timestamp,\n resolvedAt: Timestamp.nullable(),\n /** How it was resolved (decision, answers, note). */\n resolution: JsonValue.nullable(),\n});\nexport type InboxItem = z.infer<typeof InboxItem>;\n","import { z } from \"zod\";\n\n/**\n * Project autonomy modes, the software factory and the dark factory (§10.1). The factory loop\n * itself lives in `factory-api.ts` and `factory-pipeline.ts`.\n */\n\n/** The mode ids, in ladder order. */\nexport const AUTONOMY_MODES = [\"manual\", \"assisted\", \"software_factory\", \"dark_factory\"] as const;\n\n/** The id the software factory had before 0.6 (\"autopilot\"); still read from old events. */\nconst LEGACY_SOFTWARE_FACTORY = \"autopilot\";\n\n/**\n * A ladder climbed one step at a time:\n * - `manual`: you find work and merge; you drive every session.\n * - `assisted` (default): you, the PM and automations find work; you merge.\n * - `software_factory`: issues filed on GitHub (by you or trusted people) are classified as a\n * bug, a feature or a docs change and run through that pipeline by a pool of agents, ending\n * in a pull request with test results and screenshots. You merge, unless auto-merge is on.\n * - `dark_factory`: the software factory plus a scheduled scout that reviews the app against\n * the vision and files the issues itself.\n *\n * `autopilot` (the software factory's id before 0.6) is still accepted and read as\n * `software_factory`, so old events and API clients keep working.\n */\nexport const AutonomyMode = z.preprocess(\n (v) => (v === LEGACY_SOFTWARE_FACTORY ? \"software_factory\" : v),\n z.enum(AUTONOMY_MODES),\n);\nexport type AutonomyMode = z.infer<typeof AutonomyMode>;\n\n/** Default location of a project's vision file, relative to the repo root. */\nexport const DEFAULT_VISION_PATH = \".codeden/VISION.md\";\n\n/** A GitHub login as typed by a person: trimmed, without a leading `@`. */\nconst GithubLogin = z\n .string()\n .trim()\n .transform((s) => s.replace(/^@/, \"\"))\n .pipe(z.string().regex(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})(?:\\[bot\\])?$/, \"Not a GitHub login\"));\n\n/**\n * Limits and policy of the software and dark factory, enforced by the server (never left to\n * agent judgement).\n */\nexport const FactoryLimits = z.object({\n /** Agents working at once (the swarm): builders, reviewers, the scout and area reviewers. */\n maxConcurrentSessions: z.int().positive().default(2),\n /** Automatic merges per day (only while `autoMerge` is on). */\n maxMergesPerDay: z.int().nonnegative().default(5),\n /** Daily spend budget; either or both may be set. */\n dailyBudget: z\n .object({\n tokens: z.int().positive().optional(),\n usd: z.number().positive().optional(),\n })\n .prefault({}),\n /**\n * What counts against the daily budget: `factory` (default) is the factory's own sessions\n * (builders, reviewers, the scout, reverts); `project` is every session in the project.\n */\n budgetScope: z.enum([\"factory\", \"project\"]).default(\"factory\"),\n /** Pause the loop after this many failed merge checks or reverts in a row. */\n pauseAfterConsecutiveFailures: z.int().positive().default(3),\n /** Globs that always escalate to a human (auth, payments, migrations, infra, licensing). */\n protectedPaths: z.array(z.string()).default([]),\n /** Deploys/releases are off unless explicitly enabled. */\n allowDeploys: z.boolean().default(false),\n /**\n * Merge pull requests automatically once every merge check passes. Off (the default): the\n * factory stops at \"ready to merge\" and you merge on GitHub. Work from an untrusted author\n * that was let in by hand is never merged automatically, whatever this says.\n */\n autoMerge: z.boolean().default(false),\n /**\n * GitHub logins whose issues the factory takes on by itself. The account CodeDen uses on\n * GitHub is always trusted. Issues from anyone else (on a public repository: anyone at all)\n * are listed as ignored and only taken on when you, or the PM at your request, let one in.\n */\n trustedAuthors: z.array(GithubLogin).max(200).default([]),\n});\nexport type FactoryLimits = z.infer<typeof FactoryLimits>;\n\n/** State of a project's factory loop. */\nexport const FactoryLoopState = z.enum([\n \"idle\",\n \"discovering\",\n \"building\",\n \"verifying\",\n \"paused\",\n \"stopped\",\n]);\nexport type FactoryLoopState = z.infer<typeof FactoryLoopState>;\n","import { z } from \"zod\";\nimport { AutonomyLevel, Id, ProviderId, Timestamp } from \"../common\";\nimport { AutonomyMode, DEFAULT_VISION_PATH, FactoryLimits } from \"../factory\";\n\n/**\n * Something re-detecting a project's folder found that CodeDen does not apply on its own (§9).\n * `github_remote_missing`: a `github` project's folder no longer has a GitHub `origin` (removed,\n * pointing at another host, or no git checkout at all). The project keeps its GitHub\n * coordinates until the user restores the remote or disconnects GitHub.\n */\nexport const ProjectRemoteWarning = z.object({\n code: z.literal(\"github_remote_missing\"),\n /** What `origin` points at now, credentials removed; null when there is no `origin`. */\n remoteUrl: z.string().nullable(),\n detectedAt: Timestamp,\n});\nexport type ProjectRemoteWarning = z.infer<typeof ProjectRemoteWarning>;\n\nconst projectBase = {\n id: Id,\n name: z.string().min(1),\n /** Short, filesystem-safe name used in worktree paths (`wt/<slug>/...`). */\n slug: z.string().regex(/^[a-z0-9][a-z0-9-]{0,39}$/),\n /** Absolute path of the main checkout. */\n path: z.string().min(1),\n defaultBranch: z.string().nullable(),\n /** Overrides the global default provider for new agent sessions. */\n defaultProvider: ProviderId.nullable(),\n /** Overrides the global default per-session autonomy level (§11.2). */\n autonomy: AutonomyLevel.nullable(),\n /** Project autonomy mode (§10.1). */\n autonomyMode: AutonomyMode.default(\"assisted\"),\n /** Vision file, relative to the repo root; required for the software and dark factory. */\n visionPath: z.string().min(1).default(DEFAULT_VISION_PATH),\n factoryLimits: FactoryLimits.prefault({}),\n /** Stops this project's factory loop and all its sessions. */\n killSwitch: z.boolean().default(false),\n /** IANA timezone for cron automations; machine timezone when null. */\n timezone: z.string().nullable(),\n /**\n * Pinned projects are listed above the rest (§13). Defaults to false so events written\n * before pinning existed still parse.\n */\n pinned: z.boolean().default(false),\n /**\n * Manual position in the project list, lowest first (§13). Only the relative order within\n * the pinned and unpinned groups matters; ties fall back to the name. Set by\n * `projects.reordered`; archived projects keep theirs.\n */\n sortOrder: z.int().nonnegative().default(0),\n /**\n * Set when re-detection found the folder's git remote out of step with the project (see\n * `ProjectRemoteWarning`); absent when all is well. Cleared by the next detection that finds\n * the GitHub remote again, or by disconnecting GitHub.\n */\n remoteWarning: ProjectRemoteWarning.optional(),\n createdAt: Timestamp,\n updatedAt: Timestamp,\n archivedAt: Timestamp.nullable(),\n};\n\n/** GitHub repository coordinates for a `github` project. */\nexport const GitHubRepo = z.object({\n owner: z.string().min(1),\n repo: z.string().min(1),\n remoteUrl: z.string().min(1),\n defaultBranch: z.string().min(1),\n});\nexport type GitHubRepo = z.infer<typeof GitHubRepo>;\n\n/**\n * A project. `github` projects get the full issue/PR/evidence flow; `local` projects\n * (no GitHub remote) get sessions, worktrees, checkpoints, diffs and automations only (§9).\n * The kind is detected when the project is added and again later (on server start, after\n * agent turns in local projects, on demand): a folder that gains a GitHub `origin` becomes a\n * `github` project. Losing the remote never downgrades a project on its own.\n */\nexport const Project = z.discriminatedUnion(\"kind\", [\n z.object({ ...projectBase, kind: z.literal(\"github\"), github: GitHubRepo }),\n z.object({ ...projectBase, kind: z.literal(\"local\") }),\n]);\nexport type Project = z.infer<typeof Project>;\nexport type ProjectKind = Project[\"kind\"];\n\ntype Orderable = Pick<Project, \"id\" | \"name\" | \"pinned\" | \"sortOrder\">;\n\n/**\n * The canonical project order (§13): pinned first, then `sortOrder`, then name, then id.\n * The server lists projects in this order and the UI keeps it when applying live events.\n */\nexport function compareProjects(a: Orderable, b: Orderable): number {\n if (a.pinned !== b.pinned) return a.pinned ? -1 : 1;\n if (a.sortOrder !== b.sortOrder) return a.sortOrder - b.sortOrder;\n if (a.name !== b.name) return a.name < b.name ? -1 : 1;\n return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n}\n\n/** A sorted copy of `projects` in the canonical order. */\nexport function sortProjects<T extends Orderable>(projects: readonly T[]): T[] {\n return [...projects].sort(compareProjects);\n}\n","import { z } from \"zod\";\nimport { Id, Timestamp } from \"./common\";\n\n/**\n * Situational awareness and conflict handling (§8.4). Every unit of work (a session or an\n * automation run) is described in data so the orchestrator and PMs always know what is\n * running, and starting work never silently duplicates work already in progress.\n */\n\n/** Who started a unit of work. `id` is the user/session/automation id where applicable. */\nexport const StartedBy = z.object({\n kind: z.enum([\"user\", \"orchestrator\", \"pm\", \"automation\"]),\n id: z.string().optional(),\n /**\n * Who else hears when the work finishes or fails: `orchestrator` when a PM started it for a\n * request the orchestrator passed on (§8.2), so the result reaches whoever asked for it.\n */\n reportTo: z.literal(\"orchestrator\").optional(),\n});\nexport type StartedBy = z.infer<typeof StartedBy>;\n\n/**\n * Stable identifier of *what* the work is, used for conflict detection:\n * `automation:security-audit`, `issue:142`, `pr:57`, or one derived from the request.\n */\nexport const WorkKey = z\n .string()\n .min(1)\n .max(200)\n .regex(/^[a-z][a-z0-9_-]*:\\S.*$/, \"Expected <kind>:<id>, e.g. issue:142\");\nexport type WorkKey = z.infer<typeof WorkKey>;\n\n/** Where the work happens: a project, optionally narrowed to paths or a named area. */\nexport const WorkScope = z.object({\n projectId: Id.nullable(),\n paths: z.array(z.string()).optional(),\n /** Free-form area, e.g. `auth`, `ui`, `dependencies`. */\n area: z.string().optional(),\n});\nexport type WorkScope = z.infer<typeof WorkScope>;\n\n/** The latest `report_progress` call. */\nexport const WorkProgress = z.object({\n text: z.string(),\n at: Timestamp,\n});\nexport type WorkProgress = z.infer<typeof WorkProgress>;\n\n/** Fields every unit of work carries (spread into `Session` and `AutomationRun`). */\nexport const workFields = {\n startedBy: StartedBy,\n /** One line describing the work. */\n purpose: z.string(),\n workKey: WorkKey,\n scope: WorkScope,\n progress: WorkProgress.nullable(),\n};\n\n/** Compact description of running or queued work, used in conflicts and status digests. */\nexport const WorkSummary = z.object({\n kind: z.enum([\"session\", \"automation_run\"]),\n /** Session id or automation run id. */\n id: Id,\n /** Session doing the work, when there is one. */\n sessionId: Id.nullable(),\n projectId: Id.nullable(),\n ...workFields,\n /** Session status or automation run status. */\n status: z.string(),\n startedAt: Timestamp,\n});\nexport type WorkSummary = z.infer<typeof WorkSummary>;\n\n/**\n * Result of anything that starts work (`start_session`, `run_automation`, scheduled triggers).\n * On `conflict` nothing was started; the caller picks a `ConflictResolution`.\n */\nexport const StartWorkResult = z.discriminatedUnion(\"status\", [\n z.object({\n status: z.literal(\"started\"),\n sessionId: Id,\n automationRunId: Id.optional(),\n }),\n z.object({\n status: z.literal(\"conflict\"),\n /** Running or queued work with the same `workKey` or an overlapping scope. */\n existing: z.array(WorkSummary).min(1),\n /** Inbox conflict item persisted for this attempt (user starts), resolvable later. */\n conflictId: Id.optional(),\n }),\n]);\nexport type StartWorkResult = z.infer<typeof StartWorkResult>;\n\n/**\n * How to proceed after a conflict:\n * - `wait`: queue behind the existing work.\n * - `skip`: don't start anything.\n * - `join`: send the request to the existing session as a follow-up.\n * - `force`: start anyway (a reason is required and recorded).\n */\nexport const ConflictResolution = z.enum([\"wait\", \"skip\", \"join\", \"force\"]);\nexport type ConflictResolution = z.infer<typeof ConflictResolution>;\n\n/** A caller's decision on a conflict, passed back when retrying the start. */\nexport const ConflictDecision = z.discriminatedUnion(\"resolution\", [\n z.object({ resolution: z.literal(\"wait\"), behindId: Id.optional() }),\n z.object({ resolution: z.literal(\"skip\") }),\n z.object({ resolution: z.literal(\"join\"), sessionId: Id }),\n z.object({ resolution: z.literal(\"force\"), reason: z.string().trim().min(1) }),\n]);\nexport type ConflictDecision = z.infer<typeof ConflictDecision>;\n\n/** Overlap policy for scheduled triggers when the previous run is still going (§8.4, §10). */\nexport const OverlapPolicy = z.enum([\"skip-if-running\", \"queue\", \"run-anyway\"]);\nexport type OverlapPolicy = z.infer<typeof OverlapPolicy>;\n\n/** An upcoming scheduled automation run (the \"Next\" in a project's Now / Next strip). */\nexport const ScheduledRun = z.object({\n automationId: Id,\n projectId: Id.nullable(),\n name: z.string(),\n workKey: WorkKey,\n at: Timestamp,\n /** True when a PM chose to skip this occurrence (`skip_next_run`). */\n skipped: z.boolean().default(false),\n});\nexport type ScheduledRun = z.infer<typeof ScheduledRun>;\n","import { z } from \"zod\";\nimport { ProviderId } from \"./common\";\n\n/** Dev-server definition in `.codeden/project.json`. */\nexport const DevServerConfig = z.object({\n /** Shell command that starts the dev server, e.g. `pnpm dev`. */\n command: z.string().min(1),\n /** Port the dev server listens on, when known (used for discovery). */\n port: z.int().min(1).max(65535).optional(),\n /** Working directory relative to the repo root. */\n cwd: z.string().optional(),\n});\nexport type DevServerConfig = z.infer<typeof DevServerConfig>;\n\n/**\n * `.codeden/project.json` at a repository root (§9). Read by the runner after a worktree\n * is created: `setup` commands run in the new worktree (output streamed as\n * `workspace.setup` events), `devServer` feeds dev-server discovery and `defaultProvider`\n * is reported back to the server. Unknown keys are ignored.\n */\nexport const ProjectConfigFile = z.object({\n /** Commands run in order in every new worktree, e.g. `pnpm install`. */\n setup: z.array(z.string().min(1)).default([]),\n /** A bare command string or a full definition. */\n devServer: z.union([z.string().min(1), DevServerConfig]).optional(),\n defaultProvider: ProviderId.optional(),\n});\nexport type ProjectConfigFile = z.infer<typeof ProjectConfigFile>;\n\n/** Normalize `devServer` to its object form. */\nexport function devServerOf(config: ProjectConfigFile): DevServerConfig | undefined {\n const value = config.devServer;\n if (value === undefined) return undefined;\n return typeof value === \"string\" ? { command: value } : value;\n}\n","import { z } from \"zod\";\nimport { AutonomyLevel, Id, ProviderId, ReasoningEffort, Role, Timestamp } from \"./common\";\nimport { ApprovalDecider, ApprovalDecision } from \"./items\";\n\n/**\n * What a provider can do (§7.1). The UI and orchestration read these flags and never branch\n * on the provider id (Principle 5).\n */\nexport const ProviderCapabilities = z.object({\n /** Sessions can be resumed from `resumeToken()`. */\n resume: z.boolean(),\n /** Input can be injected into a running turn. */\n steer: z.boolean(),\n interrupt: z.boolean(),\n /** Tool approvals can be routed to CodeDen. */\n approvals: z.boolean(),\n /** The agent can ask structured questions. */\n userQuestions: z.boolean(),\n /** Subagents surface as child threads. */\n subagents: z.boolean(),\n /** The conversation can be rolled back to an earlier turn. */\n rollback: z.boolean(),\n /**\n * A conversation can be forked, leaving the original untouched: the runner's `provider.fork`\n * copies it into a new one (a new resume token), and `SessionOptions.forkFrom` does the same\n * as a session opens.\n */\n fork: z.boolean(),\n /** Image attachments are accepted as input. */\n images: z.boolean(),\n planMode: z.boolean(),\n reasoningEffort: z.boolean(),\n /** MCP servers can be injected (required for CodeDen tools). */\n mcp: z.boolean(),\n skills: z.boolean(),\n /**\n * An autonomy change reaches a running turn from its next tool call. When false (or absent),\n * a running turn keeps its autonomy and the change applies from the next turn.\n */\n liveAutonomy: z.boolean().optional(),\n /**\n * The `read_only` permission level is enforced natively: no file edits, no writing shell\n * commands, no commits or pushes (§11.2). When false (or absent), sessions on this provider\n * cannot use `read_only`.\n */\n readOnly: z.boolean().optional(),\n});\nexport type ProviderCapabilities = z.infer<typeof ProviderCapabilities>;\n\n/** A model a provider offers. */\nexport const ModelInfo = z.object({\n id: z.string(),\n /**\n * The concrete model id this entry runs today, when the provider reports it and it differs\n * from `id` (an alias such as `opus` → `claude-opus-5-5`). Lets a stored full id match the\n * alias entry that covers it.\n */\n resolvedId: z.string().optional(),\n label: z.string(),\n description: z.string().optional(),\n efforts: z.array(ReasoningEffort).default([]),\n defaultEffort: ReasoningEffort.optional(),\n isDefault: z.boolean().optional(),\n contextWindow: z.int().positive().optional(),\n});\nexport type ModelInfo = z.infer<typeof ModelInfo>;\n\n/** Static description of a provider adapter as loaded by a runner. */\nexport const ProviderInfo = z.object({\n id: ProviderId,\n displayName: z.string(),\n capabilities: ProviderCapabilities,\n models: z.array(ModelInfo).default([]),\n});\nexport type ProviderInfo = z.infer<typeof ProviderInfo>;\n\n/**\n * A copy of a tool that exists on disk but does not run, e.g. an npm shim whose package was\n * removed. Reported so the user can reinstall it or delete the leftover file (§14).\n */\nexport const BrokenExecutable = z.object({\n /** The file that was found, e.g. `C:\\Users\\x\\AppData\\Roaming\\npm\\claude.cmd`. */\n path: z.string(),\n /** What is wrong, as a phrase that follows the path: \"points at a missing package\". */\n reason: z.string(),\n /** The file a shim or link points at, when that is what is missing. */\n target: z.string().optional(),\n});\nexport type BrokenExecutable = z.infer<typeof BrokenExecutable>;\n\n/** A problem found while detecting a provider, with the one action that fixes it (§14). */\nexport const ProviderIssue = z.object({\n code: z.enum([\n \"not_installed\",\n /** Found on disk, but no copy runs (see `ProviderStatus.broken`). */\n \"broken_install\",\n \"not_logged_in\",\n \"login_expiring\",\n \"version_unsupported\",\n \"detect_failed\",\n ]),\n message: z.string(),\n fix: z\n .object({\n kind: z.enum([\"install\", \"login\", \"upgrade\"]),\n /** Command to run (in an embedded terminal), e.g. `claude auth login`. */\n command: z.string(),\n })\n .optional(),\n});\nexport type ProviderIssue = z.infer<typeof ProviderIssue>;\n\n/** Result of `ProviderAdapter.detect()`: installed? version? logged in? (§14). */\nexport const ProviderStatus = z.object({\n providerId: ProviderId,\n installed: z.boolean(),\n version: z.string().nullable(),\n executablePath: z.string().nullable(),\n /** `null` when login state could not be determined. */\n loggedIn: z.boolean().nullable(),\n authMethod: z.string().nullable(),\n account: z.string().nullable(),\n loginExpiresAt: Timestamp.nullable(),\n /** False when the installed version is outside the adapter's tested range. */\n supported: z.boolean(),\n issues: z.array(ProviderIssue).default([]),\n /** Copies that were found but do not run, skipped in favour of a working one (if any). */\n broken: z.array(BrokenExecutable).optional(),\n checkedAt: Timestamp,\n});\nexport type ProviderStatus = z.infer<typeof ProviderStatus>;\n\n/** An MCP server handed to a provider session (CodeDen's local proxy, user servers). */\nexport const McpServerConfig = z.discriminatedUnion(\"transport\", [\n z.object({\n transport: z.literal(\"http\"),\n name: z.string(),\n url: z.url(),\n headers: z.record(z.string(), z.string()).optional(),\n /** Max seconds one tool call may take (long-running tools such as `ask_user`). */\n toolTimeoutSec: z.int().positive().max(86_400).optional(),\n /** Tools of this server run without approval prompts (CodeDen's own tools). */\n trusted: z.boolean().optional(),\n }),\n z.object({\n transport: z.literal(\"stdio\"),\n name: z.string(),\n command: z.string(),\n args: z.array(z.string()).default([]),\n env: z.record(z.string(), z.string()).optional(),\n }),\n]);\nexport type McpServerConfig = z.infer<typeof McpServerConfig>;\n\n/** Options for `ProviderAdapter.openSession`. */\nexport const SessionOptions = z.object({\n /** CodeDen session id. */\n sessionId: Id,\n role: Role,\n /** Working directory (worktree, repo root, or the orchestrator folder). */\n cwd: z.string().min(1),\n model: z.string().optional(),\n effort: ReasoningEffort.optional(),\n autonomy: AutonomyLevel,\n /** Extra system prompt appended to the provider's own. */\n systemPrompt: z.string().optional(),\n /** Provider session/thread id from a previous `resumeToken()`. */\n resumeToken: z.string().optional(),\n /**\n * Provider session/thread id of a conversation to fork as the session opens\n * (`capabilities.fork`): the provider copies it and the session resumes the copy, whose id\n * `resumeToken()` returns at once; the original is untouched. Ignored when `resumeToken` is\n * set, which wins. CodeDen's own forks copy the conversation earlier, in the fork request\n * (`provider.fork`), and so arrive with a `resumeToken`.\n */\n forkFrom: z.string().min(1).optional(),\n mcpServers: z.array(McpServerConfig).default([]),\n /** Extra env vars for the agent process (CodeDen secrets are never included). */\n env: z.record(z.string(), z.string()).optional(),\n /** Extra directories the agent may read/write. */\n additionalDirectories: z.array(z.string()).default([]),\n /**\n * The branch this session owns: the branch of its own worktree, never the base branch. Under\n * Auto the agent may force-push it with a lease (`git push --force-with-lease`) without an\n * approval, for example after a rebase (§11.2).\n */\n ownBranch: z.string().min(1).optional(),\n /** Start in plan mode where supported. */\n planMode: z.boolean().default(false),\n /**\n * No writes to the workspace (orchestrator and PMs, §11.2): file edits and writing commands\n * are denied natively (Claude permission policy, Codex read-only sandbox).\n */\n readOnly: z.boolean().optional(),\n});\nexport type SessionOptions = z.infer<typeof SessionOptions>;\nexport type SessionOptionsInit = z.input<typeof SessionOptions>;\n\n/** Response to an `approval_request` or `user_question` item (`ProviderSession.respond`). */\nexport const RuntimeResponse = z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"approval\"),\n decision: ApprovalDecision,\n /** Optional note passed to the agent (e.g. why it was denied). */\n message: z.string().optional(),\n /** Who decided; default the user. CodeDen's own decisions are recorded as `policy`. */\n decidedBy: ApprovalDecider.optional(),\n }),\n z.object({\n kind: z.literal(\"answer\"),\n /** Selected option labels and/or free text, keyed by question id. */\n answers: z.record(z.string(), z.array(z.string())),\n }),\n /** Withdraw the request (session stopping, request superseded). */\n z.object({ kind: z.literal(\"cancel\") }),\n]);\nexport type RuntimeResponse = z.infer<typeof RuntimeResponse>;\n","import { z } from \"zod\";\nimport { Id } from \"../common\";\n\n/** Runner-assigned tab id, unique within a session's browser context (`t1`, `t2`, ...). */\nexport const BrowserTabId = z.string().min(1).max(100);\nexport type BrowserTabId = z.infer<typeof BrowserTabId>;\n\n/** One tab of a session's browser context. */\nexport const BrowserTab = z.object({\n tabId: BrowserTabId,\n url: z.string(),\n title: z.string(),\n /** The tab shown in the panel and targeted when a command omits `tabId`. */\n active: z.boolean(),\n});\nexport type BrowserTab = z.infer<typeof BrowserTab>;\n\n/** CDP modifier bitmask: Alt = 1, Ctrl = 2, Meta = 4, Shift = 8. */\nexport const BrowserModifiers = z.int().min(0).max(15);\n\n/**\n * Aria ref from a `browser.snapshot` (`e2`, or `f1e3` inside an iframe). Refs resolve\n * against the latest snapshot of the tab.\n */\nexport const BrowserElementRef = z.string().regex(/^(f\\d+)?e\\d+$/);\n\n/**\n * Pointer input from the panel. `x`/`y` are in the coordinate space of the frame as it\n * is displayed (`frameWidth` x `frameHeight`); the runner maps them onto the page viewport.\n */\nexport const BrowserMouseInput = z.object({\n type: z.enum([\"mouse.move\", \"mouse.down\", \"mouse.up\", \"mouse.wheel\"]),\n x: z.number(),\n y: z.number(),\n frameWidth: z.number().positive(),\n frameHeight: z.number().positive(),\n /**\n * Page viewport (CSS pixels) of the frame the user pointed at, from its metadata. The\n * runner maps against it, so input stays exact while a resize is in flight.\n */\n viewportWidth: z.number().positive().optional(),\n viewportHeight: z.number().positive().optional(),\n button: z.enum([\"none\", \"left\", \"middle\", \"right\"]).optional(),\n clickCount: z.int().min(0).max(3).optional(),\n /** Wheel deltas in page CSS pixels (`mouse.wheel`). */\n deltaX: z.number().optional(),\n deltaY: z.number().optional(),\n modifiers: BrowserModifiers.optional(),\n});\nexport type BrowserMouseInput = z.infer<typeof BrowserMouseInput>;\n\n/** Keyboard input from the panel, mirroring DOM `KeyboardEvent` fields. */\nexport const BrowserKeyInput = z.object({\n type: z.enum([\"key.down\", \"key.up\", \"key.char\"]),\n /** DOM `key`, e.g. `a`, `Enter`, `ArrowLeft`. */\n key: z.string().min(1).max(40),\n /** DOM `code`, e.g. `KeyA`. */\n code: z.string().max(40).optional(),\n /** Text the key produces (printable keys). */\n text: z.string().max(10).optional(),\n modifiers: BrowserModifiers.optional(),\n});\nexport type BrowserKeyInput = z.infer<typeof BrowserKeyInput>;\n\n/** Insert text at the focused element as if typed by an IME (paste-like). */\nexport const BrowserTextInput = z.object({\n type: z.literal(\"text.insert\"),\n text: z.string().max(100_000),\n});\nexport type BrowserTextInput = z.infer<typeof BrowserTextInput>;\n\n/** Human input forwarded from the panel to the active tab. */\nexport const BrowserInput = z.union([BrowserMouseInput, BrowserKeyInput, BrowserTextInput]);\nexport type BrowserInput = z.infer<typeof BrowserInput>;\n\n/** A console message (or uncaught page error) captured from a tab. Bounded per session. */\nexport const BrowserConsoleEntry = z.object({\n /** Monotonic per session; pass as `since` to page through new entries. */\n id: z.int().nonnegative(),\n tabId: BrowserTabId,\n /** `log`, `info`, `warning`, `error`, `debug`, ..., or `pageerror`. */\n level: z.string(),\n text: z.string(),\n url: z.string().optional(),\n line: z.int().optional(),\n ts: z.string(),\n});\nexport type BrowserConsoleEntry = z.infer<typeof BrowserConsoleEntry>;\n\n/** A network request made by a tab. Bounded per session. */\nexport const BrowserNetworkEntry = z.object({\n id: z.int().nonnegative(),\n tabId: BrowserTabId,\n method: z.string(),\n url: z.string(),\n resourceType: z.string(),\n /** HTTP status; null while pending or when the request failed. */\n status: z.int().nullable(),\n /** Failure text (`net::ERR_...`) when the request failed. */\n failure: z.string().nullable(),\n ts: z.string(),\n durationMs: z.number().nullable(),\n});\nexport type BrowserNetworkEntry = z.infer<typeof BrowserNetworkEntry>;\n\n/** Screencast frame metadata from CDP `Page.screencastFrame` (CSS pixels). */\nexport const BrowserFrameMetadata = z.object({\n /** Seconds since epoch when the frame was produced. */\n timestamp: z.number().optional(),\n deviceWidth: z.number(),\n deviceHeight: z.number(),\n pageScaleFactor: z.number(),\n offsetTop: z.number(),\n scrollOffsetX: z.number(),\n scrollOffsetY: z.number(),\n});\nexport type BrowserFrameMetadata = z.infer<typeof BrowserFrameMetadata>;\n\n/**\n * What backs a session's browser (§12.2): the runner's own Chromium (`runner`, shown as a\n * screencast), or native views in the desktop app (`native`, §17 Phase 2), which the runner\n * drives through the app's per-session CDP relay. Agents use the same primitives on both.\n */\nexport const BrowserEngine = z.enum([\"runner\", \"native\"]);\nexport type BrowserEngine = z.infer<typeof BrowserEngine>;\n\n/** The header that carries a relay secret (never part of the URL, so it is never logged). */\nexport const BROWSER_RELAY_SECRET_HEADER = \"x-codeden-relay-secret\";\n\n/**\n * The desktop app's CDP relay for one session's native views (§17): a loopback WebSocket that\n * sees only that session's views, never the CodeDen window. The runner connects with the\n * secret in `BROWSER_RELAY_SECRET_HEADER`.\n */\nexport const BrowserRelayEndpoint = z.object({\n /** `ws://127.0.0.1:<port>/cdp/<sessionId>`. */\n url: z.string().regex(/^ws:\\/\\/127\\.0\\.0\\.1:\\d{1,5}\\/cdp\\/[A-Za-z0-9_-]{1,200}$/),\n /** Random per-session secret. */\n secret: z.string().min(32).max(200),\n});\nexport type BrowserRelayEndpoint = z.infer<typeof BrowserRelayEndpoint>;\n\n/**\n * A cookie carried from native views to the runner's Chromium when the desktop app quits\n * (the subset of CDP `Network.CookieParam` both sides understand). `expires` is seconds since\n * the epoch; absent for session cookies.\n */\nexport const BrowserCookie = z.object({\n name: z.string().max(4_096),\n value: z.string().max(16_384),\n domain: z.string().min(1).max(1_000),\n path: z.string().max(4_096),\n expires: z.number().optional(),\n httpOnly: z.boolean(),\n secure: z.boolean(),\n sameSite: z.enum([\"Strict\", \"Lax\", \"None\"]).optional(),\n});\nexport type BrowserCookie = z.infer<typeof BrowserCookie>;\n\n/** A tab moved to the runner's Chromium on hand-off: reopened at its URL. */\nexport const BrowserHandoffTab = z.object({\n url: z.string().max(8_000),\n /** The tab the panel showed. */\n active: z.boolean(),\n});\nexport type BrowserHandoffTab = z.infer<typeof BrowserHandoffTab>;\n\nconst TabTarget = { sessionId: Id, tabId: BrowserTabId.optional() };\n\n/** `browser.*` commands (§12.2), spread into `RunnerCommand`. */\nexport const BrowserCommands = [\n /**\n * Open (or reuse) the session's browser context; opens a first tab (at `url`) if none. With\n * `relay`, a session that has no browser yet is backed by the desktop app's native views\n * through that relay (`native` engine); without it, by the runner's Chromium. A session that\n * is already open keeps its engine.\n */\n z.object({\n name: z.literal(\"browser.open\"),\n sessionId: Id,\n url: z.string().optional(),\n relay: BrowserRelayEndpoint.optional(),\n }),\n /**\n * Move the session's browser to the runner's own Chromium (the desktop app is quitting): its\n * relay connection is dropped without closing the native views, `cookies` are added to a new\n * context and each tab reopens at its URL. Unsaved page state is lost. Replaces whatever the\n * session had open.\n */\n z.object({\n name: z.literal(\"browser.handoff\"),\n sessionId: Id,\n tabs: z.array(BrowserHandoffTab).max(50),\n cookies: z.array(BrowserCookie).max(5_000),\n }),\n /** Navigate a tab (default: the active one). Bare `host:port` gets `http://`. */\n z.object({ name: z.literal(\"browser.navigate\"), ...TabTarget, url: z.string() }),\n /** Close the session's context and all its tabs. */\n z.object({ name: z.literal(\"browser.close\"), sessionId: Id }),\n z.object({\n name: z.literal(\"browser.history\"),\n ...TabTarget,\n action: z.enum([\"back\", \"forward\", \"reload\"]),\n }),\n z.object({ name: z.literal(\"browser.tabs.list\"), sessionId: Id }),\n z.object({ name: z.literal(\"browser.tabs.open\"), sessionId: Id, url: z.string().optional() }),\n z.object({ name: z.literal(\"browser.tabs.close\"), sessionId: Id, tabId: BrowserTabId }),\n z.object({ name: z.literal(\"browser.tabs.activate\"), sessionId: Id, tabId: BrowserTabId }),\n /**\n * Set the viewport of every tab in the session, now and for tabs opened later: CSS size\n * plus device scale factor (the viewer's `devicePixelRatio`). The runner clamps both to\n * its limits and sizes the screencast to match; the result is what it applied.\n */\n z.object({\n name: z.literal(\"browser.viewport\"),\n sessionId: Id,\n width: z.int().min(1).max(7680),\n height: z.int().min(1).max(4320),\n /** Default 1. */\n deviceScaleFactor: z.number().min(0.25).max(8).optional(),\n }),\n /**\n * Add (`watching: true`) or remove a panel viewer. Frames stream as `browser.frame` while\n * at least one viewer watches; the screencast pauses when the last one leaves.\n */\n z.object({\n name: z.literal(\"browser.screencast\"),\n sessionId: Id,\n viewerId: z.string().min(1).max(200),\n watching: z.boolean(),\n quality: z.int().min(10).max(100).optional(),\n maxWidth: z.int().min(100).max(7680).optional(),\n maxHeight: z.int().min(100).max(4320).optional(),\n maxFps: z.int().min(1).max(60).optional(),\n }),\n /** Forward human input to the active tab. */\n z.object({ name: z.literal(\"browser.input\"), sessionId: Id, input: BrowserInput }),\n /** Open `http://localhost:<port><path>` in a new tab of the session. */\n z.object({\n name: z.literal(\"browser.devServer\"),\n sessionId: Id,\n port: z.int().min(1).max(65535),\n path: z.string().startsWith(\"/\").optional(),\n }),\n /** Accessibility snapshot (YAML) with element refs for click/type. */\n z.object({ name: z.literal(\"browser.snapshot\"), ...TabTarget }),\n z.object({\n name: z.literal(\"browser.click\"),\n ...TabTarget,\n ref: BrowserElementRef,\n button: z.enum([\"left\", \"middle\", \"right\"]).optional(),\n doubleClick: z.boolean().optional(),\n }),\n /** Fill an editable element by ref; `submit` presses Enter afterwards. */\n z.object({\n name: z.literal(\"browser.type\"),\n ...TabTarget,\n ref: BrowserElementRef,\n text: z.string().max(100_000),\n submit: z.boolean().optional(),\n }),\n /** Press a key or chord on the focused element, e.g. `Enter`, `Control+A`. */\n z.object({ name: z.literal(\"browser.press\"), ...TabTarget, key: z.string().min(1).max(60) }),\n /** PNG screenshot of the viewport, the full page, or one element (`ref`) to an absolute path. */\n z.object({\n name: z.literal(\"browser.screenshot\"),\n ...TabTarget,\n path: z.string().min(1),\n fullPage: z.boolean().optional(),\n ref: BrowserElementRef.optional(),\n }),\n /** Console messages and/or network requests captured since `since` (exclusive). */\n z.object({\n name: z.literal(\"browser.logs\"),\n ...TabTarget,\n /** Default `all`. */\n kind: z.enum([\"console\", \"network\", \"all\"]).optional(),\n since: z.int().nonnegative().optional(),\n limit: z.int().min(1).max(1000).optional(),\n }),\n /** Evaluate a JS expression or function source in the tab (guarded: timeout, size cap). */\n z.object({\n name: z.literal(\"browser.evaluate\"),\n ...TabTarget,\n expression: z.string().min(1).max(20_000),\n }),\n /** Wait for a selector, visible text, or network idle (exactly one). */\n z.object({\n name: z.literal(\"browser.wait\"),\n ...TabTarget,\n selector: z.string().min(1).optional(),\n text: z.string().min(1).optional(),\n networkIdle: z.boolean().optional(),\n timeoutMs: z.int().min(1).max(120_000).optional(),\n }),\n] as const;\n\nconst Empty = z.object({});\nconst TabResult = z.object({ tab: BrowserTab });\n\n/** Result schemas for `browser.*` commands, spread into `RunnerCommandResults`. */\nexport const BrowserCommandResults = {\n /**\n * `cdpUrl` is the runner Chromium's CDP endpoint on 127.0.0.1 (null for native views).\n * `engine` is absent from older runners (`runner`).\n */\n \"browser.open\": z.object({\n cdpUrl: z.string().nullable(),\n tabs: z.array(BrowserTab).optional(),\n engine: BrowserEngine.optional(),\n }),\n \"browser.handoff\": z.object({ tabs: z.array(BrowserTab) }),\n \"browser.navigate\": z.object({\n url: z.string().optional(),\n status: z.int().nullable().optional(),\n }),\n \"browser.close\": Empty,\n \"browser.history\": z.object({ url: z.string() }),\n \"browser.tabs.list\": z.object({ tabs: z.array(BrowserTab), engine: BrowserEngine.optional() }),\n \"browser.tabs.open\": TabResult,\n \"browser.tabs.close\": Empty,\n \"browser.tabs.activate\": Empty,\n /**\n * The viewport the runner applied after clamping (absent from older runners). `fixed`: the\n * size is not emulated and can't follow a viewer (native views follow the desktop panel), so\n * every viewer fits the frames inside its panel.\n */\n \"browser.viewport\": z.object({\n width: z.int().positive().optional(),\n height: z.int().positive().optional(),\n deviceScaleFactor: z.number().positive().optional(),\n fixed: z.boolean().optional(),\n }),\n \"browser.screencast\": z.object({ viewers: z.int().nonnegative() }),\n \"browser.input\": Empty,\n \"browser.devServer\": TabResult,\n \"browser.snapshot\": z.object({\n tabId: BrowserTabId,\n url: z.string(),\n title: z.string(),\n snapshot: z.string(),\n truncated: z.boolean(),\n }),\n \"browser.click\": Empty,\n \"browser.type\": Empty,\n \"browser.press\": Empty,\n \"browser.screenshot\": z.object({\n path: z.string(),\n width: z.int().positive(),\n height: z.int().positive(),\n bytes: z.int().positive(),\n }),\n \"browser.logs\": z.object({\n console: z.array(BrowserConsoleEntry),\n network: z.array(BrowserNetworkEntry),\n }),\n /** JSON-serialized result (truncated to the size cap). */\n \"browser.evaluate\": z.object({ json: z.string(), truncated: z.boolean() }),\n \"browser.wait\": z.object({ matched: z.boolean() }),\n};\n","import { z } from \"zod\";\nimport { McpServerSpec } from \"../agent-config\";\nimport {\n MCP_TEST_MAX_TIMEOUT_MS,\n McpServerTestResult,\n McpStdioEnv,\n} from \"../agent-config-mcp-test\";\nimport { AutonomyLevel, Id, ProviderId, ReasoningEffort } from \"../common\";\nimport { UserInput } from \"../input\";\nimport { ProjectConfigFile } from \"../project-config\";\nimport { ProviderInfo, ProviderStatus, RuntimeResponse, SessionOptions } from \"../provider\";\nimport { BrowserCommandResults, BrowserCommands } from \"./browser\";\n\n/** Terminal (node-pty) id, unique per runner. */\nexport const PtyId = z.string().min(1).max(100);\n\n/** Most characters of a failed setup command's output kept in `workspace.prepare` results. */\nexport const SETUP_TAIL_LIMIT = 2000;\n\n/** Index of a turn checkpoint: 0 is the baseline at session start, n the end of turn n. */\nexport const CheckpointIndex = z.int().nonnegative();\n\n/** Per-file change summary of a diff. */\nexport const DiffFileStat = z.object({\n path: z.string(),\n /** Previous path for renames and copies. */\n oldPath: z.string().optional(),\n status: z.enum([\"added\", \"modified\", \"deleted\", \"renamed\", \"copied\", \"type_changed\"]),\n additions: z.int().nonnegative(),\n deletions: z.int().nonnegative(),\n binary: z.boolean(),\n});\nexport type DiffFileStat = z.infer<typeof DiffFileStat>;\n\n/**\n * Commands the server sends to a runner (§4.3), discriminated on `name`.\n * Each has a matching result schema in `RunnerCommandResults`.\n */\nexport const RunnerCommand = z.discriminatedUnion(\"name\", [\n /** Report sessions, terminals and journal state. */\n z.object({ name: z.literal(\"runner.status\") }),\n /** Finish or pause running turns, then stop accepting work (before an upgrade). */\n z.object({\n name: z.literal(\"runner.drain\"),\n reason: z.string(),\n /** Max time to wait for running turns before interrupting them. Default 5 minutes. */\n timeoutMs: z.int().positive().optional(),\n /** Exit the process once drained, so the server starts a fresh runner (upgrades). */\n exitWhenDrained: z.boolean().optional(),\n }),\n /** Runtime configuration pushed by the server after each handshake. */\n z.object({\n name: z.literal(\"runner.configure\"),\n /** Where the local MCP proxy forwards to (the server's `/mcp`); `null` disables it. */\n mcpUpstreamUrl: z.url().nullable(),\n }),\n /** Exit the runner process after closing sessions and terminals. */\n z.object({ name: z.literal(\"runner.shutdown\") }),\n /**\n * Detect installed providers (all when `providerId` is omitted). Also refreshes their model\n * lists: in the background, or before answering when `waitForModels` is set.\n */\n z.object({\n name: z.literal(\"provider.detect\"),\n providerId: ProviderId.optional(),\n /** Answer only once the model lists are refreshed, and include them as `providers`. */\n waitForModels: z.boolean().optional(),\n }),\n /** One tool-less utility-model call (§7.4) through a provider's `utilityModel()`. */\n z.object({\n name: z.literal(\"provider.oneShot\"),\n providerId: ProviderId,\n prompt: z.string().min(1),\n system: z.string().optional(),\n /** Provider model id; the provider's small default when omitted. */\n model: z.string().optional(),\n timeoutMs: z.int().positive().max(300_000).optional(),\n }),\n /**\n * Copy a conversation into a new one (`capabilities.fork`): the result is the copy's resume\n * token; the original is untouched. Fails with `unsupported` for a provider that can't fork.\n */\n z.object({\n name: z.literal(\"provider.fork\"),\n providerId: ProviderId,\n /** The resume token of the conversation to copy. */\n resumeToken: z.string().min(1),\n /** An existing folder of the project, for providers that run a process to fork. */\n cwd: z.string().min(1),\n }),\n /** Create or reuse the working directory for a session (worktree + setup commands). */\n z.object({\n name: z.literal(\"workspace.prepare\"),\n sessionId: Id,\n repoPath: z.string().min(1),\n strategy: z.enum([\"worktree\", \"repo_root\", \"existing\"]),\n /** Target directory for `worktree` / `existing`. */\n path: z.string().optional(),\n branch: z.string().optional(),\n baseRef: z.string().optional(),\n setupCommands: z.array(z.string()).default([]),\n /** Used for the default worktree path `<home>/wt/<projectSlug>/<sessionShort>`. */\n projectSlug: z\n .string()\n .regex(/^[a-z0-9][a-z0-9-]{0,39}$/)\n .optional(),\n /** `git fetch origin` before branching (when an `origin` remote exists). */\n fetch: z.boolean().optional(),\n /** Run `.codeden/project.json` `setup` commands before `setupCommands`. Default true. */\n runProjectSetup: z.boolean().optional(),\n /**\n * A forked session's starting point: once a new worktree is created, its files are made to\n * match this checkpoint of another session (as uncommitted changes on top of the branch)\n * before setup commands run. Ignored when the worktree already existed.\n */\n restoreCheckpoint: z.object({ sessionId: Id, index: CheckpointIndex }).optional(),\n }),\n /**\n * Remove a session worktree (and optionally its branch). Idempotent: a missing path, or a\n * half-deleted folder under `<home>/wt/<project>/<session>` that is no longer a git worktree,\n * ends `removed`. A folder under `<home>/wt` is moved to `<home>/wt/.trash` (all or nothing)\n * and deleted in the background; nothing is ever deleted through a symlink or junction.\n * Fails with `worktree_dirty` (uncommitted changes, not forced), `worktree_locked`,\n * `worktree_in_use` (a file is held open; the worktree is untouched, retry later) or\n * `not_a_worktree` (left alone: not this repository's worktree, or outside `<home>/wt`).\n */\n z.object({\n name: z.literal(\"workspace.remove\"),\n repoPath: z.string().min(1),\n path: z.string().min(1),\n deleteBranch: z.string().optional(),\n /** Remove even with uncommitted changes. */\n force: z.boolean().optional(),\n }),\n /** Open a provider session; optionally start the first turn. */\n z.object({\n name: z.literal(\"session.start\"),\n sessionId: Id,\n providerId: ProviderId,\n options: SessionOptions,\n input: UserInput.optional(),\n /** Snapshot the cwd at session start and every turn end (§9). Default true in git repos. */\n checkpoints: z.boolean().optional(),\n }),\n /** Start a new turn. */\n z.object({ name: z.literal(\"session.send\"), sessionId: Id, input: UserInput }),\n /** Inject input into the running turn (requires `capabilities.steer`). */\n z.object({ name: z.literal(\"session.steer\"), sessionId: Id, input: UserInput }),\n z.object({ name: z.literal(\"session.interrupt\"), sessionId: Id }),\n /** Answer an approval request or user question. */\n z.object({\n name: z.literal(\"session.respond\"),\n sessionId: Id,\n requestId: Id,\n response: RuntimeResponse,\n }),\n /** Close the provider session (resumable later via its resume token). */\n z.object({ name: z.literal(\"session.stop\"), sessionId: Id }),\n /**\n * Change model/effort for the next turn, and/or the autonomy level (§11.2): from the next\n * tool call when the provider reports `liveAutonomy`, otherwise from the next turn. `planMode`\n * turns plan mode on or off (`capabilities.planMode`). `unsupported` when the provider\n * cannot change a requested setting live.\n */\n z.object({\n name: z.literal(\"session.configure\"),\n sessionId: Id,\n model: z.string().nullable().optional(),\n effort: ReasoningEffort.nullable().optional(),\n autonomy: AutonomyLevel.optional(),\n planMode: z.boolean().optional(),\n }),\n z.object({\n name: z.literal(\"pty.open\"),\n ptyId: PtyId,\n cwd: z.string().min(1),\n shell: z.string().optional(),\n args: z.array(z.string()).optional(),\n cols: z.int().positive(),\n rows: z.int().positive(),\n env: z.record(z.string(), z.string()).optional(),\n sessionId: Id.optional(),\n }),\n z.object({ name: z.literal(\"pty.input\"), ptyId: PtyId, data: z.string() }),\n z.object({\n name: z.literal(\"pty.resize\"),\n ptyId: PtyId,\n cols: z.int().positive(),\n rows: z.int().positive(),\n }),\n z.object({ name: z.literal(\"pty.close\"), ptyId: PtyId }),\n /** Scrollback and state of a terminal, for (re)attaching a view. */\n z.object({ name: z.literal(\"pty.attach\"), ptyId: PtyId }),\n /** `browser.*` (§12.2), defined in `./browser`. */\n ...BrowserCommands,\n /** Snapshot the worktree into `refs/codeden/checkpoints/<session>/<n>` (§9). */\n z.object({\n name: z.literal(\"git.checkpoint\"),\n sessionId: Id,\n cwd: z.string(),\n index: z.int().nonnegative(),\n }),\n z.object({ name: z.literal(\"git.status\"), cwd: z.string() }),\n /** Unified diff `fromRef..toRef`; without `toRef`, against the working tree incl. untracked files. */\n z.object({\n name: z.literal(\"git.diff\"),\n cwd: z.string(),\n fromRef: z.string(),\n toRef: z.string().optional(),\n }),\n z.object({\n name: z.literal(\"git.branches\"),\n cwd: z.string(),\n includeRemote: z.boolean().optional(),\n }),\n /** Stage (all changes, or `paths`) and commit. */\n z.object({\n name: z.literal(\"git.commit\"),\n cwd: z.string(),\n message: z.string().min(1),\n paths: z.array(z.string()).optional(),\n }),\n z.object({\n name: z.literal(\"git.push\"),\n cwd: z.string(),\n /** Default `origin`. */\n remote: z.string().optional(),\n /** Default: the current branch. */\n branch: z.string().optional(),\n /** Set the upstream (`-u`). Default true. */\n setUpstream: z.boolean().optional(),\n forceWithLease: z.boolean().optional(),\n }),\n z.object({\n name: z.literal(\"checkpoint.list\"),\n cwd: z.string(),\n sessionId: Id,\n /**\n * First wait for checkpoints the runner is still writing for this session (the one for a\n * turn that just ended), so the list ends with the state the conversation has reached.\n */\n settled: z.boolean().optional(),\n }),\n /** Diff between two checkpoints; without `to`, against the current working tree. */\n z.object({\n name: z.literal(\"checkpoint.diff\"),\n cwd: z.string(),\n sessionId: Id,\n from: CheckpointIndex,\n to: CheckpointIndex.optional(),\n }),\n /** Restore files (all, or `paths`) to their state at a checkpoint without touching the index. */\n z.object({\n name: z.literal(\"checkpoint.restoreFiles\"),\n cwd: z.string(),\n sessionId: Id,\n index: CheckpointIndex,\n paths: z.array(z.string()).optional(),\n }),\n /** Listening localhost ports of processes started by this runner, plus `probe`d ports. */\n z.object({\n name: z.literal(\"ports.list\"),\n probe: z.array(z.int().min(1).max(65535)).optional(),\n }),\n /**\n * Connection test of an MCP server (§12.4): start it (stdio) or reach its URL (http/sse),\n * run `initialize` and `tools/list`, then stop it. A failing server is an `ok: false` result.\n */\n z.object({\n name: z.literal(\"mcp.test\"),\n spec: McpServerSpec,\n /** Working directory of a stdio server without its own `cwd`; the runner's home when omitted. */\n cwd: z.string().min(1).optional(),\n /** Expand `${VAR}` and `${VAR:-default}` from the runner's environment, as Claude Code does. */\n expandEnv: z.boolean(),\n /** How a stdio server's environment is built; `inherit` when omitted. */\n stdioEnv: McpStdioEnv.optional(),\n /** Default `MCP_TEST_DEFAULT_TIMEOUT_MS`. */\n timeoutMs: z.int().positive().max(MCP_TEST_MAX_TIMEOUT_MS).optional(),\n }),\n]);\nexport type RunnerCommand = z.infer<typeof RunnerCommand>;\nexport type RunnerCommandName = RunnerCommand[\"name\"];\nexport type RunnerCommandOf<N extends RunnerCommandName> = Extract<RunnerCommand, { name: N }>;\n\n/** A session currently hosted by the runner. */\nexport const RunnerSessionInfo = z.object({\n sessionId: Id,\n providerId: ProviderId,\n state: z.enum([\"idle\", \"running\", \"closing\"]),\n resumeToken: z.string().nullable(),\n});\nexport type RunnerSessionInfo = z.infer<typeof RunnerSessionInfo>;\n\nconst Empty = z.object({});\n\n/** Result schema for each command. */\nexport const RunnerCommandResults = {\n \"runner.status\": z.object({\n sessions: z.array(RunnerSessionInfo),\n ptys: z.array(PtyId),\n journal: z.object({ lastSeq: z.int().nonnegative(), unacked: z.int().nonnegative() }),\n draining: z.boolean(),\n }),\n \"runner.drain\": Empty,\n \"runner.configure\": z.object({ mcpProxyUrl: z.string().nullable() }),\n \"runner.shutdown\": Empty,\n \"provider.detect\": z.object({\n statuses: z.array(ProviderStatus),\n /** Every provider after the refresh; set when the command asked for `waitForModels`. */\n providers: z.array(ProviderInfo).optional(),\n }),\n \"provider.oneShot\": z.object({ text: z.string(), model: z.string() }),\n \"provider.fork\": z.object({ resumeToken: z.string().min(1) }),\n \"workspace.prepare\": z.object({\n cwd: z.string(),\n branch: z.string().nullable(),\n created: z.boolean(),\n /** Parsed `.codeden/project.json`, when present and valid. */\n config: ProjectConfigFile.nullable().optional(),\n /** Setup commands that ran, in order (stops at the first failure). */\n setup: z\n .array(\n z.object({\n command: z.string(),\n /** Null when the command was killed (timed out) before it exited. */\n exitCode: z.int().nullable(),\n ok: z.boolean(),\n /**\n * The end of a failed command's output (at most `SETUP_TAIL_LIMIT` characters), so\n * the server can tell the agent why setup failed. Absent for commands that succeeded\n * and from older runners.\n */\n outputTail: z.string().max(SETUP_TAIL_LIMIT).optional(),\n }),\n )\n .optional(),\n }),\n \"workspace.remove\": z.object({\n removed: z.boolean(),\n /** A forced removal deleted uncommitted changes (absent from older runners). */\n discardedChanges: z.boolean().optional(),\n }),\n \"session.start\": z.object({ resumeToken: z.string().nullable() }),\n \"session.send\": Empty,\n \"session.steer\": Empty,\n \"session.interrupt\": Empty,\n \"session.respond\": Empty,\n \"session.stop\": Empty,\n \"session.configure\": Empty,\n \"pty.open\": z.object({ pid: z.int() }),\n \"pty.input\": Empty,\n \"pty.resize\": Empty,\n \"pty.close\": Empty,\n \"pty.attach\": z.object({\n pid: z.int(),\n cols: z.int().positive(),\n rows: z.int().positive(),\n /** Bounded scrollback to replay into a fresh view. */\n scrollback: z.string(),\n exited: z.boolean(),\n exitCode: z.int().nullable(),\n }),\n ...BrowserCommandResults,\n \"git.checkpoint\": z.object({ ref: z.string(), commit: z.string() }),\n \"git.status\": z.object({\n branch: z.string().nullable(),\n ahead: z.int().nonnegative(),\n behind: z.int().nonnegative(),\n files: z.array(z.object({ path: z.string(), status: z.string() })),\n }),\n \"git.diff\": z.object({ diff: z.string(), files: z.array(DiffFileStat).optional() }),\n \"git.branches\": z.object({\n current: z.string().nullable(),\n defaultBranch: z.string().nullable(),\n branches: z.array(\n z.object({\n name: z.string(),\n remote: z.boolean(),\n commit: z.string(),\n upstream: z.string().nullable(),\n }),\n ),\n }),\n /** `commit` is null when there was nothing to commit. */\n \"git.commit\": z.object({ commit: z.string().nullable() }),\n \"git.push\": z.object({ remote: z.string(), branch: z.string() }),\n \"checkpoint.list\": z.object({\n checkpoints: z.array(\n z.object({\n index: CheckpointIndex,\n ref: z.string(),\n commit: z.string(),\n createdAt: z.string(),\n }),\n ),\n }),\n \"checkpoint.diff\": z.object({ diff: z.string(), files: z.array(DiffFileStat) }),\n \"checkpoint.restoreFiles\": z.object({\n restored: z.array(z.string()),\n deleted: z.array(z.string()),\n }),\n \"ports.list\": z.object({\n ports: z.array(\n z.object({\n port: z.int().min(1).max(65535),\n pid: z.int().nullable(),\n url: z.string(),\n }),\n ),\n }),\n \"mcp.test\": McpServerTestResult,\n} satisfies Record<RunnerCommandName, z.ZodType>;\n\n/** Result type of a command: `RunnerCommandResult<\"session.start\">`. */\nexport type RunnerCommandResult<N extends RunnerCommandName> = z.infer<\n (typeof RunnerCommandResults)[N]\n>;\n","import { z } from \"zod\";\nimport { Id, Timestamp } from \"./common\";\nimport { MessageSender, UserInput } from \"./input\";\nimport { CheckpointIndex, PtyId } from \"./runner/commands\";\n\n/**\n * Workbench data (§9, §12): turn checkpoints, workspace setup output, persisted message\n * queues, structured session results, diffs, git operations and the terminal channel.\n */\n\n/** A turn checkpoint recorded by the server from the runner's `checkpoint.created` (§9). */\nexport const Checkpoint = z.object({\n sessionId: Id,\n /** 0 is the baseline at session start; n the end of turn n. */\n index: CheckpointIndex,\n /** `refs/codeden/checkpoints/<session>/<index>`. */\n ref: z.string(),\n commit: z.string(),\n /** The turn that ended; null for the baseline. */\n turnId: Id.nullable(),\n createdAt: Timestamp,\n});\nexport type Checkpoint = z.infer<typeof Checkpoint>;\n\n/** One worktree setup command (`.codeden/project.json` `setup`, §9) and its latest output. */\nexport const SetupStep = z.object({\n command: z.string(),\n status: z.enum([\"running\", \"succeeded\", \"failed\"]),\n /** Tail of the command's output (bounded). */\n output: z.string(),\n updatedAt: Timestamp,\n});\nexport type SetupStep = z.infer<typeof SetupStep>;\n\n/** Who queued a message: the same senders as `MessageSender`. */\nexport const QueueSender = MessageSender;\nexport type QueueSender = MessageSender;\n\n/** A message sent while a turn was running, waiting to be delivered (survives restarts). */\nexport const QueuedMessage = z.object({\n id: Id,\n sessionId: Id,\n input: UserInput,\n /** Who queued it. Events written before senders were recorded were all the user's. */\n from: QueueSender.default(\"user\"),\n createdAt: Timestamp,\n});\nexport type QueuedMessage = z.infer<typeof QueuedMessage>;\n\n/** `GET /api/sessions/:id/queue`: the session's queued messages, next to be delivered first. */\nexport const QueuedMessageList = z.object({ messages: z.array(QueuedMessage) });\nexport type QueuedMessageList = z.infer<typeof QueuedMessageList>;\n\n/**\n * `PATCH /api/sessions/:id/queue/:messageId`: replace a queued message's text (attachments\n * stay). Answers 409 `already_sent` once delivery has taken the message.\n */\nexport const EditQueuedMessageRequest = z.object({ text: z.string().max(200_000) });\nexport type EditQueuedMessageRequest = z.infer<typeof EditQueuedMessageRequest>;\n\n/**\n * `POST /api/sessions/:id/queue/:messageId/send-now`: steer the running turn with a queued\n * message (needs `capabilities.steer`). Answers 409 `no_turn` when no turn is running (the\n * queue sends it next) and 409 `unsupported` when the provider cannot steer.\n * `DELETE /api/sessions/:id/queue/:messageId` answers `{ ok: true }`; both answer 409\n * `already_sent` once delivery has taken the message.\n */\nexport const SendQueuedNowResponse = z.object({ status: z.literal(\"steered\") });\nexport type SendQueuedNowResponse = z.infer<typeof SendQueuedNowResponse>;\n\n/** Structured result an agent reports with the `finish` tool (§8.3). */\nexport const SessionResult = z.object({\n outcome: z.enum([\"success\", \"partial\", \"failed\", \"blocked\"]),\n summary: z.string().min(1),\n /** Files the agent changed, when it reports them. */\n changedFiles: z.array(z.string()).optional(),\n /** Tests or checks run and how they went. */\n tests: z.string().optional(),\n /** Anything a human or PM should do next. */\n nextSteps: z.array(z.string()).optional(),\n at: Timestamp,\n});\nexport type SessionResult = z.infer<typeof SessionResult>;\n\n// ---------------------------------------------------------------------------- diffs\n\n/** What a diff covers: the whole session, one turn, or uncommitted changes in the worktree. */\nexport const DiffScope = z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"session\") }),\n z.object({ kind: z.literal(\"turn\"), turnId: Id }),\n z.object({ kind: z.literal(\"uncommitted\") }),\n]);\nexport type DiffScope = z.infer<typeof DiffScope>;\n\n/** One file of a diff, with its unified patch. */\nexport const DiffFile = z.object({\n path: z.string(),\n previousPath: z.string().optional(),\n change: z.enum([\"add\", \"modify\", \"delete\", \"rename\"]),\n additions: z.int().nonnegative(),\n deletions: z.int().nonnegative(),\n binary: z.boolean().optional(),\n /** Unified patch for this file. */\n patch: z.string(),\n});\nexport type DiffFile = z.infer<typeof DiffFile>;\n\n/** `POST /api/sessions/:id/diff` (body: `DiffScope`). */\nexport const DiffResult = z.object({\n scope: DiffScope,\n files: z.array(DiffFile),\n /** Turns that have checkpoints, oldest first. */\n turns: z.array(z.object({ id: Id, index: CheckpointIndex, label: z.string(), at: Timestamp })),\n});\nexport type DiffResult = z.infer<typeof DiffResult>;\n\n/** `GET /api/sessions/:id/checkpoints`. */\nexport const CheckpointList = z.object({ checkpoints: z.array(Checkpoint) });\nexport type CheckpointList = z.infer<typeof CheckpointList>;\n\n/**\n * `POST /api/sessions/:id/restore`: put files (all, or `paths`) back to their state at a\n * checkpoint. `turnId` restores to the state *before* that turn; `index` names a checkpoint.\n */\nexport const RestoreFilesRequest = z\n .object({\n turnId: Id.optional(),\n index: CheckpointIndex.optional(),\n paths: z.array(z.string().min(1)).optional(),\n })\n .refine((r) => (r.turnId === undefined) !== (r.index === undefined), {\n message: \"Pass exactly one of turnId or index\",\n });\nexport type RestoreFilesRequest = z.infer<typeof RestoreFilesRequest>;\n\nexport const RestoreFilesResponse = z.object({\n index: CheckpointIndex,\n restored: z.array(z.string()),\n deleted: z.array(z.string()),\n});\nexport type RestoreFilesResponse = z.infer<typeof RestoreFilesResponse>;\n\n// ---------------------------------------------------------------------------- git\n\n/** `GET /api/sessions/:id/git/status`. */\nexport const GitStatusResponse = z.object({\n branch: z.string().nullable(),\n baseBranch: z.string().nullable(),\n ahead: z.int().nonnegative(),\n behind: z.int().nonnegative(),\n files: z.array(z.object({ path: z.string(), status: z.string() })),\n});\nexport type GitStatusResponse = z.infer<typeof GitStatusResponse>;\n\n/** `POST /api/sessions/:id/git/commit`: stage (all, or `paths`) and commit. */\nexport const GitCommitRequest = z.object({\n message: z.string().min(1).max(10_000),\n paths: z.array(z.string().min(1)).optional(),\n});\nexport type GitCommitRequest = z.infer<typeof GitCommitRequest>;\n\n/** `commit` is null when there was nothing to commit. */\nexport const GitCommitResponse = z.object({ commit: z.string().nullable() });\nexport type GitCommitResponse = z.infer<typeof GitCommitResponse>;\n\n/** `POST /api/sessions/:id/git/push`. */\nexport const GitPushRequest = z.object({\n remote: z.string().min(1).optional(),\n forceWithLease: z.boolean().optional(),\n});\nexport type GitPushRequest = z.infer<typeof GitPushRequest>;\n\nexport const GitPushResponse = z.object({ remote: z.string(), branch: z.string() });\nexport type GitPushResponse = z.infer<typeof GitPushResponse>;\n\n// ---------------------------------------------------------------------------- terminal\n\n/**\n * `GET /ws/pty?sessionId=&ptyId=&command=&cols=&rows=` opens (or, with `ptyId`, attaches to)\n * a runner terminal. Without `sessionId` the terminal opens in the CodeDen home folder.\n * Server -> client frames are plain text (terminal output) except for `TerminalServerMessage`\n * control frames, which are JSON objects prefixed with `\\u0000`.\n */\nexport const TerminalQuery = z.object({\n sessionId: Id.optional(),\n /** Attach to an existing terminal instead of opening a new one. */\n ptyId: PtyId.optional(),\n /** Run this command in the shell once it starts (e.g. `claude auth login`). */\n command: z.string().max(2_000).optional(),\n cols: z.coerce.number().int().positive().max(1_000).default(120),\n rows: z.coerce.number().int().positive().max(500).default(30),\n});\nexport type TerminalQuery = z.infer<typeof TerminalQuery>;\n\n/** Client -> server messages on a terminal socket (JSON text frames). */\nexport const TerminalClientMessage = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"input\"), data: z.string().max(1_000_000) }),\n z.object({\n type: z.literal(\"resize\"),\n cols: z.int().positive().max(1_000),\n rows: z.int().positive().max(500),\n }),\n /** Kill the terminal process (closing the socket only detaches). */\n z.object({ type: z.literal(\"kill\") }),\n]);\nexport type TerminalClientMessage = z.infer<typeof TerminalClientMessage>;\n\n/** Server -> client control frames (sent as `\\u0000` + JSON). */\nexport const TerminalServerMessage = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"opened\"), ptyId: PtyId, pid: z.int(), attached: z.boolean() }),\n z.object({ type: z.literal(\"exited\"), ptyId: PtyId, exitCode: z.int().nullable() }),\n z.object({ type: z.literal(\"error\"), message: z.string() }),\n]);\nexport type TerminalServerMessage = z.infer<typeof TerminalServerMessage>;\n\n/** Prefix that marks a terminal control frame. */\nexport const TERMINAL_CONTROL_PREFIX = \"\\u0000\";\n\n// ---------------------------------------------------------------------------- utility\n\n/** `POST /api/utility/speech-summary`: compress a final message for read-aloud (§11.3). */\nexport const SpeechSummaryRequest = z.object({ text: z.string().min(1).max(200_000) });\nexport type SpeechSummaryRequest = z.infer<typeof SpeechSummaryRequest>;\n\n/** `source: \"plain\"` when the utility model was off or failed and the text was only cleaned. */\nexport const SpeechSummaryResponse = z.object({\n text: z.string(),\n source: z.enum([\"utility\", \"plain\"]),\n});\nexport type SpeechSummaryResponse = z.infer<typeof SpeechSummaryResponse>;\n","import { z } from \"zod\";\nimport {\n AutonomyLevel,\n ErrorInfo,\n GitHubIssueRef,\n GitHubPrRef,\n Id,\n ProviderId,\n ReasoningEffort,\n Role,\n Timestamp,\n} from \"../common\";\nimport { Item } from \"../items\";\nimport { workFields } from \"../work\";\nimport { SessionResult } from \"../workbench\";\n\n/**\n * Session lifecycle.\n * - `created`: row exists, nothing started on a runner yet.\n * - `queued`: waiting behind conflicting work (§8.4 `wait`).\n * - `starting`: workspace prepared / provider process launching.\n * - `running`: a turn is in progress.\n * - `waiting`: blocked on the user (approval or question).\n * - `idle`: between turns, ready for input.\n * - `interrupted`: cut off (runner restart, crash); resumable.\n * - `completed` / `failed` / `stopped`: terminal.\n */\nexport const SessionStatus = z.enum([\n \"created\",\n \"queued\",\n \"starting\",\n \"running\",\n \"waiting\",\n \"idle\",\n \"interrupted\",\n \"completed\",\n \"failed\",\n \"stopped\",\n]);\nexport type SessionStatus = z.infer<typeof SessionStatus>;\n\n/**\n * Where a forked session came from: the source session and the checkpoint its worktree\n * started from (null when the source had none yet). The fork continues the source's\n * conversation through the provider's native fork; the source is left as it was.\n */\nexport const ForkOrigin = z.object({\n sessionId: Id,\n checkpoint: z.int().nonnegative().nullable(),\n});\nexport type ForkOrigin = z.infer<typeof ForkOrigin>;\n\n/** An agent session of any role (§8.1). */\nexport const Session = z.object({\n id: Id,\n /** Null for the orchestrator. */\n projectId: Id.nullable(),\n role: Role,\n /** The session that started this one (PM for agents, orchestrator for PMs). */\n parentSessionId: Id.nullable(),\n /** Who/why/what (§8.4): startedBy, purpose, workKey, scope, progress. */\n ...workFields,\n title: z.string().nullable(),\n provider: ProviderId,\n model: z.string().nullable(),\n effort: ReasoningEffort.nullable(),\n autonomy: AutonomyLevel,\n /**\n * True while the session is planning (where the provider reports `capabilities.planMode`):\n * the agent explores and proposes a plan, and implements only once the plan is approved.\n * Absent means false.\n */\n planMode: z.boolean().optional(),\n status: SessionStatus,\n /** Directory the agent runs in. */\n cwd: z.string(),\n /** Set when the session owns a worktree under `~/.codeden/wt/`. */\n worktreePath: z.string().nullable(),\n branch: z.string().nullable(),\n baseBranch: z.string().nullable(),\n issue: GitHubIssueRef.nullable(),\n pr: GitHubPrRef.nullable(),\n /** Provider resume token (session/thread id). */\n resumeToken: z.string().nullable(),\n /** Runner currently hosting the session. */\n runnerId: z.string().nullable(),\n automationRunId: Id.nullable(),\n /** The session's root thread, once the provider started it. */\n rootThreadId: Id.nullable(),\n /** Structured result from the agent's `finish` tool, once reported. */\n result: SessionResult.nullable().optional(),\n /** When the session was archived: hidden from the sidebar, its worktree cleaned up. */\n archivedAt: Timestamp.nullable().optional(),\n /**\n * When CodeDen removed the session's worktree (archive or inactivity cleanup). The branch and\n * checkpoints stay; the worktree is recreated from the branch on the next message.\n */\n worktreeRemovedAt: Timestamp.nullable().optional(),\n /** Set when the session was forked from another one (its conversation and code). */\n forkedFrom: ForkOrigin.nullable().optional(),\n createdAt: Timestamp,\n updatedAt: Timestamp,\n endedAt: Timestamp.nullable(),\n});\nexport type Session = z.infer<typeof Session>;\n\n/** Thread projection (§6 `threads`). */\nexport const Thread = z.object({\n id: Id,\n sessionId: Id,\n parentThreadId: Id.nullable(),\n parentItemId: Id.nullable(),\n title: z.string().nullable(),\n agentType: z.string().nullable(),\n createdAt: Timestamp,\n});\nexport type Thread = z.infer<typeof Thread>;\n\nexport const TurnStatus = z.enum([\"running\", \"completed\", \"failed\", \"interrupted\"]);\nexport type TurnStatus = z.infer<typeof TurnStatus>;\n\n/** Turn projection (§6 `turns`). */\nexport const Turn = z.object({\n id: Id,\n threadId: Id,\n sessionId: Id,\n status: TurnStatus,\n startedAt: Timestamp,\n completedAt: Timestamp.nullable(),\n error: ErrorInfo.nullable(),\n});\nexport type Turn = z.infer<typeof Turn>;\n\n/** Item projection (§6 `items`): the latest state of an item plus its location. */\nexport const ItemRecord = z.object({\n sessionId: Id,\n threadId: Id,\n turnId: Id,\n /** Order within the thread. */\n position: z.int().nonnegative(),\n item: Item,\n createdAt: Timestamp,\n updatedAt: Timestamp,\n});\nexport type ItemRecord = z.infer<typeof ItemRecord>;\n","import { z } from \"zod\";\nimport {\n AutonomyLevel,\n ErrorInfo,\n Id,\n ProviderId,\n QuietHours,\n ReasoningEffort,\n Timestamp,\n} from \"../common\";\nimport { OverlapPolicy, workFields } from \"../work\";\n\n/** Events an automation can be triggered by (§10). */\nexport const AutomationEventName = z.enum([\n \"session.finished\",\n \"session.failed\",\n \"session.needs_input\",\n \"pr.opened\",\n \"pr.merged\",\n \"pr.checks_failed\",\n \"pr.review_requested\",\n \"issue.opened\",\n \"issue.labeled\",\n \"issue.commented\",\n]);\nexport type AutomationEventName = z.infer<typeof AutomationEventName>;\n\n/** When an automation fires. */\nexport const AutomationTrigger = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"cron\"),\n /** Cron expression (croner syntax). */\n expression: z.string().min(1),\n /** IANA timezone; defaults to the project's timezone. */\n timezone: z.string().optional(),\n }),\n z.object({\n type: z.literal(\"event\"),\n event: AutomationEventName,\n filter: z\n .object({\n labels: z.array(z.string()).optional(),\n branches: z.array(z.string()).optional(),\n authors: z.array(z.string()).optional(),\n })\n .optional(),\n }),\n z.object({ type: z.literal(\"manual\") }),\n]);\nexport type AutomationTrigger = z.infer<typeof AutomationTrigger>;\n\n/**\n * How the PM's issue triage applies a decision (§10): labels per decision, whether to comment\n * and close, and whether a `ready` issue may start a session without asking (assisted mode and\n * above only; otherwise the user gets a \"Should I take this on?\" inbox decision).\n */\nexport const TriagePolicy = z.object({\n labels: z\n .object({\n ready: z.array(z.string().min(1)).default([\"triage:ready\"]),\n needs_info: z.array(z.string().min(1)).default([\"needs-info\"]),\n unsafe: z.array(z.string().min(1)).default([\"triage:unsafe\"]),\n out_of_scope: z.array(z.string().min(1)).default([\"out-of-scope\"]),\n duplicate: z.array(z.string().min(1)).default([\"duplicate\"]),\n })\n .prefault({}),\n /** Post a short comment explaining the decision. */\n comment: z.boolean().default(true),\n /** Close duplicates and out-of-scope issues as \"not planned\". */\n closeRejected: z.boolean().default(false),\n /** Start a session for `ready` issues without asking (never in `manual` projects). */\n autoStart: z.boolean().default(false),\n /** Provider, model and autonomy for sessions started from triage. */\n provider: ProviderId.optional(),\n model: z.string().optional(),\n autonomy: AutonomyLevel.optional(),\n});\nexport type TriagePolicy = z.infer<typeof TriagePolicy>;\n\n/** What an automation does when it fires. */\nexport const AutomationAction = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"start_session\"),\n /** Prompt template (Markdown, `{{placeholders}}` filled from the trigger context). */\n prompt: z.string().min(1),\n title: z.string().optional(),\n provider: ProviderId.optional(),\n model: z.string().optional(),\n effort: ReasoningEffort.optional(),\n autonomy: AutonomyLevel.optional(),\n }),\n z.object({\n type: z.literal(\"message_pm\"),\n message: z.string().min(1),\n }),\n z.object({\n type: z.literal(\"triage\"),\n policy: TriagePolicy.optional(),\n /** Extra guidance for the PM, appended to the triage request. */\n instructions: z.string().optional(),\n }),\n]);\nexport type AutomationAction = z.infer<typeof AutomationAction>;\n\n/** Which projects an automation applies to. */\nexport const AutomationTarget = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"project\"), projectId: Id }),\n z.object({ type: z.literal(\"all_projects\") }),\n]);\nexport type AutomationTarget = z.infer<typeof AutomationTarget>;\n\n/** Safety rails on automation runs (§10). */\nexport const AutomationGuards = z.object({\n /** What a trigger does while previous work with the same workKey is still going (§8.4). */\n overlapPolicy: OverlapPolicy.default(\"skip-if-running\"),\n maxConcurrent: z.int().positive().default(1),\n maxPerDay: z.int().positive().nullable().default(null),\n quietHours: QuietHours.nullable().default(null),\n /** Run once for missed schedules after downtime. */\n catchUpMissed: z.boolean().default(false),\n});\nexport type AutomationGuards = z.infer<typeof AutomationGuards>;\n\n/** Who created a database automation (§10). */\nexport const AutomationCreator = z.enum([\"user\", \"pm\", \"import\"]);\nexport type AutomationCreator = z.infer<typeof AutomationCreator>;\n\n/** An automation: trigger + action + target + guards. Off by default. */\nexport const Automation = z.object({\n id: Id,\n name: z.string().min(1),\n description: z.string().nullable(),\n enabled: z.boolean().default(false),\n /** Where the definition lives. */\n source: z.enum([\"builtin\", \"global_file\", \"project_file\", \"database\"]),\n /** Template this was created from, if any. */\n templateId: z.string().nullable(),\n trigger: AutomationTrigger,\n action: AutomationAction,\n target: AutomationTarget,\n guards: AutomationGuards.prefault({}),\n /**\n * Work key of its runs (§8.4), e.g. `automation:security-audit`; may contain\n * `{{placeholders}}` from the trigger (`automation:ci-fix:{{pr.number}}`). Defaults to\n * `automation:<template id or name slug>`.\n */\n workKey: z.string().min(1).max(200).optional(),\n /**\n * Who created a database automation: the user in the UI (`user`, the default when absent),\n * a PM through `create_automation` (`pm`), or an import of shared files (`import`).\n */\n createdBy: AutomationCreator.optional(),\n createdAt: Timestamp,\n updatedAt: Timestamp,\n});\nexport type Automation = z.infer<typeof Automation>;\n\n/**\n * Frontmatter of an automation template file (Markdown + YAML; the body is the prompt).\n * Lives in `~/.codeden/automations/` or a repo's `.codeden/automations/`.\n */\nexport const AutomationTemplateFrontmatter = z.object({\n name: z.string().min(1),\n description: z.string().optional(),\n trigger: AutomationTrigger,\n provider: ProviderId.optional(),\n model: z.string().optional(),\n autonomy: AutonomyLevel.optional(),\n guards: AutomationGuards.partial().optional(),\n});\nexport type AutomationTemplateFrontmatter = z.infer<typeof AutomationTemplateFrontmatter>;\n\nexport const AutomationRunStatus = z.enum([\n \"queued\",\n \"running\",\n \"completed\",\n \"failed\",\n \"skipped\",\n \"cancelled\",\n]);\nexport type AutomationRunStatus = z.infer<typeof AutomationRunStatus>;\n\n/** One execution of an automation. Every run is a normal session or PM turn (§10). */\nexport const AutomationRun = z\n .object({\n id: Id,\n automationId: Id,\n projectId: Id.nullable(),\n status: AutomationRunStatus,\n triggeredBy: z.enum([\"cron\", \"event\", \"manual\", \"catch_up\"]),\n /** Who/why/what (§8.4): startedBy, purpose, workKey, scope, progress. */\n ...workFields,\n /** Set when `status` is `skipped`. */\n skipReason: z\n .enum([\n \"overlap\",\n \"concurrency\",\n \"quiet_hours\",\n \"daily_cap\",\n \"disabled\",\n \"skipped_by_pm\",\n \"conflict_skip\",\n /** An issue-intake run in a software- or dark-factory project: the factory loop owns intake. */\n \"factory_intake\",\n ])\n .nullable(),\n sessionId: Id.nullable(),\n /**\n * The issue an issue-triggered run is about. A triage run stays `running` until the PM's\n * `report_triage` for this issue arrives.\n */\n issueNumber: z.int().positive().nullable().optional(),\n startedAt: Timestamp,\n finishedAt: Timestamp.nullable(),\n error: ErrorInfo.nullable(),\n })\n .refine((run) => (run.status === \"skipped\") === (run.skipReason !== null), {\n message: \"skipReason is required exactly when status is skipped\",\n path: [\"skipReason\"],\n });\nexport type AutomationRun = z.infer<typeof AutomationRun>;\n","import { z } from \"zod\";\nimport { Id, Timestamp } from \"../common\";\n\nexport const ArtifactKind = z.enum([\"image\", \"screenshot\", \"file\", \"tool_output\", \"evidence\"]);\nexport type ArtifactKind = z.infer<typeof ArtifactKind>;\n\n/** A stored file (screenshot, generated image, shared file, full tool output) under `artifacts/`. */\nexport const Artifact = z.object({\n id: Id,\n kind: ArtifactKind,\n name: z.string(),\n mediaType: z.string(),\n /** Path relative to `<home>/artifacts/`. */\n path: z.string(),\n sizeBytes: z.int().nonnegative(),\n sha256: z\n .string()\n .regex(/^[a-f0-9]{64}$/)\n .nullable(),\n projectId: Id.nullable(),\n sessionId: Id.nullable(),\n threadId: Id.nullable(),\n itemId: Id.nullable(),\n createdAt: Timestamp,\n});\nexport type Artifact = z.infer<typeof Artifact>;\n","import { z } from \"zod\";\nimport { Id, Timestamp } from \"./common\";\n\n/**\n * The software factory's pipelines (§10.1): every piece of work is classified as a bug, a\n * feature or a docs change and runs through that type's steps:\n *\n * ```\n * Issue -> Identify type -+-> Bug: Reproduce -> Create fix -> Review fix -+-> Merge\n * +-> Feature: Analyze -> Implement -> Review -+\n * +-> Docs: Implement docs change -----------------+\n * ```\n *\n * A failed review sends the work back to the builder (the revise loop). Merging is yours unless\n * auto-merge is on. Also the dark factory's scout: its review rounds, area reviewers and findings.\n */\n\n/** The three pipelines. */\nexport const WorkType = z.enum([\"bug\", \"feature\", \"docs\"]);\nexport type WorkType = z.infer<typeof WorkType>;\n\n/** Who decided the type: a GitHub label, the utility model, keywords, the scout or a person. */\nexport const ClassifiedBy = z.enum([\n \"label\",\n \"model\",\n \"heuristic\",\n \"scout\",\n \"system\",\n \"user\",\n \"pm\",\n]);\nexport type ClassifiedBy = z.infer<typeof ClassifiedBy>;\n\nexport const Confidence = z.enum([\"high\", \"medium\", \"low\"]);\nexport type Confidence = z.infer<typeof Confidence>;\n\n/** The \"Identify type\" step's result. */\nexport const Classification = z.object({\n type: WorkType,\n confidence: Confidence,\n rationale: z.string().max(1_000),\n by: ClassifiedBy,\n at: Timestamp,\n});\nexport type Classification = z.infer<typeof Classification>;\n\n/**\n * Whether the factory may take work on by itself:\n * - `trusted`: an issue by a trusted author (or the account CodeDen uses), or work the factory\n * found itself (the scout, a failed check on the default branch, a revert);\n * - `untrusted`: an issue by anyone else; it is listed as ignored and nothing runs on it;\n * - `admitted`: an untrusted issue let in by you or by the PM at your request. It runs through\n * the pipeline but is never merged automatically.\n */\nexport const WorkTrust = z.enum([\"trusted\", \"untrusted\", \"admitted\"]);\nexport type WorkTrust = z.infer<typeof WorkTrust>;\n\n/** Outcomes of the first step of the bug (reproduce) and feature (analyze) pipelines. */\nexport const InvestigationOutcome = z.enum([\n \"reproduced\",\n \"not_reproduced\",\n \"implement\",\n \"already_done\",\n \"needs_info\",\n \"out_of_scope\",\n]);\nexport type InvestigationOutcome = z.infer<typeof InvestigationOutcome>;\n\n/** What the builder found before writing the fix or the feature. */\nexport const Investigation = z.object({\n kind: z.enum([\"reproduction\", \"analysis\"]),\n outcome: InvestigationOutcome,\n summary: z.string().max(2_000),\n /** Reproduction steps, or the spec the feature is built to. */\n details: z.string().max(12_000).nullable(),\n /** The failing test or probe that shows the bug. */\n testPath: z.string().max(500).nullable(),\n at: Timestamp,\n});\nexport type Investigation = z.infer<typeof Investigation>;\n\n/** `factory_report_reproduction`: the bug pipeline's Reproduce step. */\nexport const FactoryReproductionReport = z.object({\n reproduced: z.boolean(),\n summary: z.string().trim().min(1).max(2_000).describe(\"What you found, in a few sentences\"),\n steps: z\n .string()\n .max(4_000)\n .optional()\n .describe(\"How to reproduce it: commands or steps, in order\"),\n evidence: z\n .string()\n .max(8_000)\n .optional()\n .describe(\"The failing output, trimmed to what shows the bug\"),\n testPath: z\n .string()\n .max(500)\n .optional()\n .describe(\"The failing test or probe you wrote, relative to the repository root\"),\n});\nexport type FactoryReproductionReport = z.infer<typeof FactoryReproductionReport>;\n\n/** `factory_submit_analysis`: the feature pipeline's Analyze step. */\nexport const FactoryAnalysisReport = z\n .object({\n decision: z.enum([\"implement\", \"already_done\", \"needs_info\", \"out_of_scope\"]),\n summary: z.string().trim().min(1).max(2_000).describe(\"Your conclusion, in a few sentences\"),\n spec: z\n .string()\n .max(12_000)\n .optional()\n .describe(\"For `implement`: the spec you will build (API, behaviour, edge cases, docs)\"),\n acceptanceCriteria: z\n .array(z.string().trim().min(1).max(500))\n .min(1)\n .max(12)\n .optional()\n .describe(\"For `implement`: testable acceptance criteria\"),\n })\n .refine((r) => r.decision !== \"implement\" || (r.spec && r.acceptanceCriteria), {\n message: \"`implement` needs a spec and acceptance criteria\",\n });\nexport type FactoryAnalysisReport = z.infer<typeof FactoryAnalysisReport>;\n\n/**\n * Where a work item is in its pipeline (what the dashboard diagram shows):\n * `intake` (waiting to be classified), `ignored` (untrusted author), `queued` (waiting for a\n * free agent), `reproduce` / `analyze` (first step of bugs and features), `implement` (fix,\n * feature or docs change), `review` (merge checks and the independent review), `merge` (ready\n * for you, merging, or watching the default branch after it), `done`, `stopped`.\n */\nexport const PipelineStep = z.enum([\n \"intake\",\n \"ignored\",\n \"queued\",\n \"reproduce\",\n \"analyze\",\n \"implement\",\n \"review\",\n \"merge\",\n \"done\",\n \"stopped\",\n]);\nexport type PipelineStep = z.infer<typeof PipelineStep>;\n\n/** The fields of a work item that decide its step. */\nexport interface PipelineStepInput {\n stage: string;\n type: WorkType | null;\n investigation: Investigation | null;\n checks: Array<{ state: string }>;\n review: { verdict: string } | null;\n}\n\n/** Whether the item's merge checks all passed (none pending or failed). */\nexport function checksPassed(item: Pick<PipelineStepInput, \"checks\">): boolean {\n return (\n item.checks.length > 0 && item.checks.every((c) => c.state === \"pass\" || c.state === \"skipped\")\n );\n}\n\n/** The pipeline step of a work item, from its stage and what it has done so far. */\nexport function pipelineStep(item: PipelineStepInput): PipelineStep {\n switch (item.stage) {\n case \"candidate\":\n return \"intake\";\n case \"ignored\":\n return \"ignored\";\n case \"backlog\":\n return \"queued\";\n case \"building\":\n if (!item.investigation && item.type === \"bug\") return \"reproduce\";\n if (!item.investigation && item.type === \"feature\") return \"analyze\";\n return \"implement\";\n case \"verifying\":\n return checksPassed(item) ? \"merge\" : \"review\";\n case \"watching\":\n case \"escalated\":\n return \"merge\";\n case \"merged\":\n return \"done\";\n default:\n return \"stopped\";\n }\n}\n\n// ---------------------------------------------------------------- the dark factory's scout\n\n/**\n * The scout's review areas: what its area reviewers look at, one long-lived reviewer session per\n * area. The code calls those sessions lenses; the UI, docs and prompts say \"area reviewer\".\n */\nexport const DiscoveryArea = z.enum([\n \"features\",\n \"ux\",\n \"performance\",\n \"tech_debt\",\n \"test_gaps\",\n \"security\",\n \"bugs\",\n \"docs\",\n]);\nexport type DiscoveryArea = z.infer<typeof DiscoveryArea>;\n\n/** One review area the scout asks for this round (`factory_plan_round`). */\nexport const ScoutLensRequest = z.object({\n area: DiscoveryArea,\n focus: z\n .string()\n .trim()\n .min(1)\n .max(1_000)\n .describe(\"What this area's reviewer should look at this round, specific to this app\"),\n});\nexport type ScoutLensRequest = z.infer<typeof ScoutLensRequest>;\n\n/** `factory_plan_round`: the review areas for this round (none: the scout reviews by itself). */\nexport const FactoryPlanRoundRequest = z.object({\n lenses: z\n .array(ScoutLensRequest)\n .max(8)\n .describe(\n \"The review areas for this round, one area reviewer each; empty to review by yourself\",\n ),\n});\nexport type FactoryPlanRoundRequest = z.infer<typeof FactoryPlanRoundRequest>;\n\n/** One improvement an area reviewer found (`factory_report_findings`). */\nexport const FactoryFinding = z.object({\n title: z.string().trim().min(3).max(200),\n summary: z\n .string()\n .trim()\n .min(1)\n .max(4_000)\n .describe(\"What is wrong or missing, and why it matters for the vision\"),\n type: WorkType,\n severity: z.enum([\"high\", \"medium\", \"low\"]).default(\"medium\"),\n acceptanceCriteria: z.array(z.string().trim().min(1).max(500)).min(1).max(12),\n /** Paths the change would touch, when known. */\n paths: z.array(z.string()).max(50).optional(),\n});\nexport type FactoryFinding = z.infer<typeof FactoryFinding>;\nexport type FactoryFindingInit = z.input<typeof FactoryFinding>;\n\n/** A finding as the round keeps it, for the scout to decide on. */\nexport const ScoutFinding = FactoryFinding.extend({\n id: z.string().min(1),\n area: DiscoveryArea,\n});\nexport type ScoutFinding = z.infer<typeof ScoutFinding>;\n\n/** `factory_file_issue`: the scout files one piece of work as a GitHub issue. */\nexport const FactoryFileIssueRequest = z.object({\n title: z.string().trim().min(3).max(200),\n summary: z\n .string()\n .trim()\n .min(1)\n .max(8_000)\n .describe(\"The issue body: what and why, grounded in the vision\"),\n type: WorkType,\n acceptanceCriteria: z.array(z.string().trim().min(1).max(500)).min(1).max(12),\n priority: z.enum([\"high\", \"normal\", \"low\"]).default(\"normal\"),\n /** Findings this issue covers. */\n findingIds: z.array(z.string()).max(20).optional(),\n});\nexport type FactoryFileIssueRequest = z.infer<typeof FactoryFileIssueRequest>;\nexport type FactoryFileIssueRequestInit = z.input<typeof FactoryFileIssueRequest>;\n\n/** One area reviewer of the current round. */\nexport const ScoutLensRun = z.object({\n area: DiscoveryArea,\n focus: z.string(),\n sessionId: Id,\n sentAt: Timestamp,\n reported: z.boolean(),\n /** When it was reminded to report (once). */\n nudgedAt: Timestamp.nullable().default(null),\n});\nexport type ScoutLensRun = z.infer<typeof ScoutLensRun>;\n\n/**\n * One review round of the scout: `planning` (the scout picks review areas), `reviewing` (the\n * area reviewers work), `filing` (the scout files the issues worth doing).\n */\nexport const ScoutRound = z.object({\n id: z.string().min(1),\n phase: z.enum([\"planning\", \"reviewing\", \"filing\"]),\n startedAt: Timestamp,\n /** When the scout was last sent work in this round (its turn must end after this). */\n sentAt: Timestamp,\n nudgedAt: Timestamp.nullable().default(null),\n lenses: z.array(ScoutLensRun).default([]),\n findings: z.array(ScoutFinding).max(60).default([]),\n filed: z.int().nonnegative().default(0),\n});\nexport type ScoutRound = z.infer<typeof ScoutRound>;\n\n/** The scout of a dark factory: its long-lived sessions and the round in progress. */\nexport const ScoutState = z.object({\n sessionId: Id.nullable().default(null),\n /** One long-lived area reviewer session per area, reused round after round. */\n lensSessions: z.partialRecord(DiscoveryArea, Id).default({}),\n round: ScoutRound.nullable().default(null),\n lastRoundAt: Timestamp.nullable().default(null),\n rounds: z.int().nonnegative().default(0),\n});\nexport type ScoutState = z.infer<typeof ScoutState>;\n\n/** The scout as the dashboard shows it. */\nexport const ScoutStatus = z.object({\n phase: z.enum([\"idle\", \"planning\", \"reviewing\", \"filing\"]),\n sessionId: Id.nullable(),\n /** The area reviewers of the current round, one per review area. */\n lenses: z.array(\n z.object({ area: DiscoveryArea, sessionId: Id, reported: z.boolean(), active: z.boolean() }),\n ),\n findings: z.int().nonnegative(),\n filed: z.int().nonnegative(),\n lastRoundAt: Timestamp.nullable(),\n /**\n * When the next round may start (it also waits for the queue to run low); null while a round\n * runs, before the first one, and when scheduled rounds are off (`minBacklog` 0).\n */\n nextRoundAt: Timestamp.nullable(),\n rounds: z.int().nonnegative(),\n /**\n * Why \"Run scout now\" (`POST /api/projects/:id/factory/scout`) can't start a round right now,\n * in plain words; null when it can.\n */\n runNowBlockedBy: z.string().nullable().default(null),\n});\nexport type ScoutStatus = z.infer<typeof ScoutStatus>;\n\n// ---------------------------------------------------------------- your decisions\n\n/** Let an ignored issue from an untrusted author in (it is never merged automatically). */\nexport const FactoryAdmitRequest = z.object({\n itemId: Id,\n /** Skip classification with a type you chose. */\n type: WorkType.optional(),\n});\nexport type FactoryAdmitRequest = z.infer<typeof FactoryAdmitRequest>;\n\n/** Correct the type of an item that has not started yet. */\nexport const FactorySetTypeRequest = z.object({\n itemId: Id,\n type: WorkType,\n reason: z.string().trim().max(500).optional(),\n});\nexport type FactorySetTypeRequest = z.infer<typeof FactorySetTypeRequest>;\n","import { z } from \"zod\";\nimport { GitHubIssueRef, GitHubPrRef, Id, ProviderId, Timestamp } from \"./common\";\nimport { AutonomyMode, FactoryLimits, FactoryLoopState } from \"./factory\";\nimport {\n Classification,\n DiscoveryArea,\n Investigation,\n PipelineStep,\n ScoutState,\n ScoutStatus,\n WorkTrust,\n WorkType,\n} from \"./factory-pipeline\";\n\n/**\n * The factory loop of software-factory and dark-factory projects (§10.1): work items, merge\n * checks, the reviewer's verdict, the loop record, the vision and the HTTP shapes of\n * `/api/.../factory`. Both modes are experimental. The pipelines themselves are in\n * `factory-pipeline.ts`.\n */\n\n/** Modes in which the factory loop runs. */\nexport const FACTORY_MODES = [\"software_factory\", \"dark_factory\"] as const satisfies AutonomyMode[];\n\n/** True for the software factory and the dark factory. */\nexport function isFactoryMode(mode: AutonomyMode): boolean {\n return (FACTORY_MODES as readonly string[]).includes(mode);\n}\n\n/** Where a work item came from: an issue, the scout, a failed check on main, a revert. */\nexport const FactoryItemSource = z.enum([\"discovery\", \"issue\", \"failed_check\", \"revert\"]);\nexport type FactoryItemSource = z.infer<typeof FactoryItemSource>;\n\n/**\n * Where a work item is in its life (the pipeline step is derived from it, see `pipelineStep`):\n * - `candidate`: received, waiting to be classified (Identify type)\n * - `ignored`: an issue by an untrusted author; nothing runs until someone lets it in\n * - `backlog`: classified, waiting for a free agent\n * - `building` (reproduce or analyze, then implement), `verifying` (merge checks, the review,\n * then ready to merge), `watching` (merged automatically, main CI watched)\n * - `merged` (done), `reverted`, `rejected` (not reproduced, declined, closed), `failed`\n * (merge checks), `escalated` (touches a protected area: yours to merge)\n */\nexport const FactoryItemStage = z.enum([\n \"candidate\",\n \"ignored\",\n \"backlog\",\n \"building\",\n \"verifying\",\n \"watching\",\n \"merged\",\n \"reverted\",\n \"rejected\",\n \"failed\",\n \"escalated\",\n]);\nexport type FactoryItemStage = z.infer<typeof FactoryItemStage>;\n\n/** The merge checks; all must pass before an automatic merge. */\nexport const MergeCheckName = z.enum([\n \"ci\",\n \"tests\",\n \"test_results\",\n \"review\",\n \"security\",\n \"ui_evidence\",\n \"size\",\n \"protected_paths\",\n]);\nexport type MergeCheckName = z.infer<typeof MergeCheckName>;\n\nexport const MergeCheckState = z.enum([\"pending\", \"pass\", \"fail\", \"skipped\"]);\nexport type MergeCheckState = z.infer<typeof MergeCheckState>;\n\n/** One recorded merge-check result. */\nexport const MergeCheck = z.object({\n name: MergeCheckName,\n state: MergeCheckState,\n detail: z.string().nullable(),\n /** A failure that needs a human (protected area) rather than a fix. */\n escalate: z.boolean().default(false),\n at: Timestamp,\n});\nexport type MergeCheck = z.infer<typeof MergeCheck>;\n\n/** Longest review summary stored with a verdict; a longer one is stored truncated. */\nexport const REVIEW_SUMMARY_MAX = 20_000;\n\n/** Ends a review summary that was cut to `REVIEW_SUMMARY_MAX`. */\nexport const REVIEW_SUMMARY_TRUNCATED = \"… (truncated)\";\n\n/**\n * A review summary as stored: unchanged up to `REVIEW_SUMMARY_MAX` characters, otherwise cut\n * to fit and ended with `REVIEW_SUMMARY_TRUNCATED`. A verdict is never lost over its length.\n */\nexport function truncateReviewSummary(summary: string): string {\n if (summary.length <= REVIEW_SUMMARY_MAX) return summary;\n let kept = summary.slice(0, REVIEW_SUMMARY_MAX - REVIEW_SUMMARY_TRUNCATED.length - 1);\n // Don't leave half of a surrogate pair (an emoji) at the cut.\n if (/[\\uD800-\\uDBFF]$/.test(kept)) kept = kept.slice(0, -1);\n return `${kept.trimEnd()} ${REVIEW_SUMMARY_TRUNCATED}`;\n}\n\n/** The independent reviewer's structured verdict (`factory_submit_review`), as stored. */\nexport const ReviewVerdict = z.object({\n verdict: z.enum([\"approve\", \"request_changes\", \"reject\"]),\n summary: z.string().min(1).max(REVIEW_SUMMARY_MAX),\n /** One entry per acceptance criterion. */\n criteria: z\n .array(z.object({ criterion: z.string(), met: z.boolean(), note: z.string().optional() }))\n .default([]),\n vision: z.object({ aligned: z.boolean(), note: z.string().optional() }),\n tests: z.object({\n adequate: z.boolean(),\n /** True when the change needs no tests (docs, config, copy). */\n notNeeded: z.boolean().optional(),\n note: z.string().optional(),\n }),\n security: z.object({ concerns: z.array(z.string()).default([]) }),\n});\nexport type ReviewVerdict = z.infer<typeof ReviewVerdict>;\nexport type ReviewVerdictInit = z.input<typeof ReviewVerdict>;\n\n/**\n * What a reviewer sends to `factory_submit_review`: a `ReviewVerdict` whose summary has no\n * upper bound, so a long review is never rejected; the tool stores it with\n * `truncateReviewSummary`.\n */\nexport const ReviewVerdictSubmission = ReviewVerdict.extend({\n summary: z\n .string()\n .min(1)\n .describe(\n `What you found, specifically. Up to ${REVIEW_SUMMARY_MAX.toLocaleString(\"en-US\")} characters are stored; anything longer is cut and marked \"${REVIEW_SUMMARY_TRUNCATED}\".`,\n ),\n});\nexport type ReviewVerdictSubmission = z.infer<typeof ReviewVerdictSubmission>;\n\n/** A work item of the factory loop. */\nexport const FactoryItem = z.object({\n id: Id,\n projectId: Id,\n /** `issue:<n>` once its issue exists (`factory:<slug>` before). */\n workKey: z.string().min(1),\n title: z.string().min(1),\n /** The issue body, or why it matters as the scout described it. */\n summary: z.string(),\n source: FactoryItemSource,\n area: DiscoveryArea.nullable(),\n acceptanceCriteria: z.array(z.string()),\n /** Priority, 0..1 (higher first); null for issues, which queue in order of arrival. */\n score: z.number().min(0).max(1).nullable(),\n stage: FactoryItemStage,\n /** The pipeline (bug, feature, docs); null until classified. */\n type: WorkType.nullable().default(null),\n classification: Classification.nullable().default(null),\n /** Whether the factory may act on it by itself (see `WorkTrust`). */\n trust: WorkTrust.default(\"trusted\"),\n /** GitHub login of the issue's author, when it came from an issue. */\n author: z.string().nullable().default(null),\n /** Who let an untrusted issue in. */\n admittedBy: z.enum([\"user\", \"pm\"]).nullable().default(null),\n /** The bug's reproduction or the feature's analysis, once the builder reported it. */\n investigation: Investigation.nullable().default(null),\n issue: GitHubIssueRef.nullable(),\n pr: GitHubPrRef.nullable(),\n builderSessionId: Id.nullable(),\n builderProvider: ProviderId.nullable(),\n reviewerSessionId: Id.nullable(),\n reviewerProvider: ProviderId.nullable(),\n /** Set when the reviewer had to run on the author's provider. */\n reviewerNote: z.string().nullable(),\n review: ReviewVerdict.nullable(),\n checks: z.array(MergeCheck),\n /** Fix rounds after failed merge checks. */\n attempts: z.int().nonnegative(),\n /** Why it was rejected, failed or escalated. */\n reason: z.string().nullable(),\n /** Last thing the loop noted about it (waiting on a conflict, merge budget, ...). */\n note: z.string().nullable(),\n mergeSha: z.string().nullable(),\n /** For revert items: the item whose merge is reverted. */\n revertOf: Id.nullable(),\n /** When the PM was asked to triage it. */\n triageRequestedAt: Timestamp.nullable(),\n /** Timestamps of nudges sent to the builder or reviewer (keyed by purpose). */\n nudges: z.record(z.string(), Timestamp).default({}),\n /**\n * Why the PM let this item go over the size limit (an initial scaffold, a stack migration:\n * work that can't be split). The size check then passes; every other check still applies.\n */\n largeChange: z.string().nullable().default(null),\n /**\n * When the factory archived the item's builder and reviewer sessions after it finished, which\n * removes their worktrees (the branch and transcript stay); null until then. Set once, so a\n * session someone unarchives stays unarchived. Retry clears it.\n */\n sessionsArchivedAt: Timestamp.nullable().default(null),\n /**\n * Sessions of attempts before a retry that weren't archived yet. The factory archives them\n * once none of them is busy (a turn is never cut off), then empties the list.\n */\n earlierSessionIds: z.array(Id).default([]),\n createdAt: Timestamp,\n updatedAt: Timestamp,\n mergedAt: Timestamp.nullable(),\n finishedAt: Timestamp.nullable(),\n});\nexport type FactoryItem = z.infer<typeof FactoryItem>;\n\n/** Size limit defaults before 0.4.4, upgraded to the current defaults when a loop is read. */\nexport const LEGACY_SIZE_LIMITS = { maxChangedLines: 800, maxChangedFiles: 40 } as const;\n\n/** Knobs of the loop beyond the required limits; all have safe defaults. */\nexport const FactoryTuning = z.object({\n /**\n * Largest change merged automatically: added + deleted lines, not counting lockfiles and\n * generated or vendored files. `null`: no limit.\n */\n maxChangedLines: z.int().positive().nullable().default(5_000),\n /** Most files changed (same files not counted). `null` (the default): no limit. */\n maxChangedFiles: z.int().positive().nullable().default(null),\n /** CI must report and pass; a repository without CI cannot auto-merge. */\n requireCi: z.boolean().default(true),\n /** Security/dependency scan run in the builder's worktree (e.g. `pnpm audit --prod`). */\n auditCommand: z.string().min(1).nullable().default(null),\n /** Revise rounds (failed review or merge checks) before an item fails. */\n maxFixAttempts: z.int().nonnegative().default(2),\n /**\n * Dark factory: the scout starts a scheduled round only when fewer items than this wait to be\n * classified or for an agent. 0 turns scheduled rounds off: only \"Run scout now\" starts one.\n */\n minBacklog: z.int().nonnegative().default(2),\n /** Dark factory: minutes between the scout's review rounds. */\n discoveryIntervalMin: z.int().positive().default(360),\n /**\n * Dark factory: most review areas the scout may use per round, each with its own long-lived\n * area reviewer session (\"Review areas per round\" in the UI).\n */\n discoveryPerRound: z.int().nonnegative().default(2),\n /** Dark factory: most issues the scout may file per round. */\n maxIssuesPerRound: z.int().positive().default(3),\n /** Dark factory: the review areas the scout may use. */\n areas: z.array(DiscoveryArea).default(DiscoveryArea.options),\n /** Provider for builders (`auto`: the project/role default). */\n builderProvider: z.union([z.literal(\"auto\"), ProviderId]).default(\"auto\"),\n /** Minutes to wait for main CI after a merge before calling it done. */\n watchTimeoutMin: z.int().positive().default(120),\n /**\n * Minutes a builder or reviewer may stay idle, after it was reminded of its step (report,\n * pull request or verdict) and ended its turn again, before the item fails. An agent waiting\n * on its own background command ends its turn and is woken when the command exits, so a turn\n * end alone doesn't mean it stopped working.\n */\n idleGraceMin: z.int().positive().default(10),\n});\nexport type FactoryTuning = z.infer<typeof FactoryTuning>;\n\n/**\n * A change to some tuning knobs. Unlike `FactoryTuning.partial()`, absent fields stay absent\n * (no defaults filled in), so saving one knob never resets the others.\n */\nexport const FactoryTuningPatch = z.object(\n Object.fromEntries(\n Object.entries(FactoryTuning.shape).map(([key, schema]) => {\n const kind = (schema as z.ZodType)._zod.def.type;\n const inner =\n kind === \"default\" || kind === \"prefault\"\n ? (schema as unknown as { unwrap(): z.ZodType }).unwrap()\n : (schema as z.ZodType);\n return [key, inner.optional()];\n }),\n ) as unknown as { [K in keyof FactoryTuning]: z.ZodOptional<z.ZodType<FactoryTuning[K]>> },\n);\nexport type FactoryTuningPatch = z.infer<typeof FactoryTuningPatch>;\n\n/** A discovery session of loops before 0.6 (kept so old loops still parse). */\nexport const DiscoveryRun = z.object({ sessionId: Id, area: DiscoveryArea, startedAt: Timestamp });\nexport type DiscoveryRun = z.infer<typeof DiscoveryRun>;\n\n/** The persisted loop of one project; resumable after a restart. */\nexport const FactoryLoop = z.object({\n projectId: Id,\n state: FactoryLoopState,\n pausedReason: z.string().nullable(),\n consecutiveFailures: z.int().nonnegative(),\n /** Local day (`YYYY-MM-DD`) the counters below belong to. */\n day: z.string(),\n mergesToday: z.int().nonnegative(),\n /** Unused since 0.6 (the scout replaced the discovery sessions). */\n discovery: z.array(DiscoveryRun).default([]),\n /** Unused since 0.6. */\n nextArea: z.int().nonnegative().default(0),\n /** Unused since 0.6 (see `scout.lastRoundAt`). */\n lastDiscoveryAt: Timestamp.nullable().default(null),\n /** The dark factory's scout. */\n scout: ScoutState.prefault({}),\n /** Day of the last daily digest. */\n lastDigestDay: z.string().nullable(),\n /** Issues opened before this are not picked up automatically. */\n enabledAt: Timestamp.nullable(),\n /** Main-branch commits whose failed checks already became items. */\n seenFailedShas: z.array(z.string()).default([]),\n tuning: FactoryTuning.prefault({}),\n lastTickAt: Timestamp.nullable(),\n updatedAt: Timestamp,\n});\nexport type FactoryLoop = z.infer<typeof FactoryLoop>;\n\n/** The daily digest (inbox item + notice to the orchestrator). */\nexport const FactoryDigest = z.object({\n id: Id,\n projectId: Id,\n day: z.string(),\n shipped: z.array(\n z.object({ itemId: Id, title: z.string(), pr: GitHubPrRef.nullable(), reverted: z.boolean() }),\n ),\n rejected: z.array(\n z.object({ itemId: Id, title: z.string(), stage: FactoryItemStage, reason: z.string() }),\n ),\n spend: z.object({\n usd: z.number().nonnegative(),\n tokens: z.int().nonnegative(),\n budgetUsd: z.number().nullable(),\n budgetTokens: z.int().nullable(),\n }),\n waiting: z.array(\n z.object({ title: z.string(), inboxItemId: Id.nullable(), itemId: Id.nullable() }),\n ),\n /** Judgement calls factory agents made on their own during the day (dark factory). */\n decisions: z\n .array(\n z.object({\n title: z.string(),\n decision: z.string(),\n needsHuman: z.boolean(),\n inboxItemId: Id,\n }),\n )\n .default([]),\n text: z.string(),\n createdAt: Timestamp,\n});\nexport type FactoryDigest = z.infer<typeof FactoryDigest>;\n\n/**\n * `factory_record_decision` (§10.1): in a dark factory nobody is watching, so a factory agent\n * that would have asked the user decides from the vision instead and records the call here.\n * It reaches the user's inbox and the daily digest so they can review or override it later;\n * nothing waits on it. `needsHuman` flags the few calls that are the user's to make\n * (protected areas, a missing or self-contradicting vision, anything irreversible outside the\n * code) without stopping the loop.\n */\nexport const FactoryDecisionRequest = z.object({\n /** What the agent would have asked. */\n question: z.string().min(1).max(2_000),\n /** What it decided. */\n decision: z.string().min(1).max(2_000),\n /** Why, grounded in the vision. */\n reasoning: z.string().min(1).max(4_000),\n needsHuman: z.boolean().default(false),\n});\nexport type FactoryDecisionRequest = z.infer<typeof FactoryDecisionRequest>;\n\n// ---------------------------------------------------------------- vision\n\n/** Protected areas parsed from the vision: path globs and topics that always need a human. */\nexport const ProtectedAreas = z.object({\n globs: z.array(z.string()),\n topics: z.array(z.string()),\n});\nexport type ProtectedAreas = z.infer<typeof ProtectedAreas>;\n\nexport const ParsedVision = z.object({\n goals: z.array(z.string()),\n users: z.array(z.string()),\n principles: z.array(z.string()),\n outOfScope: z.array(z.string()),\n qualityBar: z.array(z.string()),\n protectedAreas: ProtectedAreas,\n});\nexport type ParsedVision = z.infer<typeof ParsedVision>;\n\n/** `GET /api/projects/:id/vision`: the template when the file does not exist yet. */\nexport const VisionResponse = z.object({\n path: z.string(),\n exists: z.boolean(),\n contents: z.string(),\n parsed: ParsedVision,\n /**\n * After a save in a GitHub project: the pull request (`codeden/vision`) that commits the\n * vision, so agents' worktrees (cut from the default branch) get it once it merges.\n */\n pr: GitHubPrRef.nullable().optional(),\n /** Why the vision could not be committed to GitHub (it is still saved locally). */\n shareError: z.string().nullable().optional(),\n});\nexport type VisionResponse = z.infer<typeof VisionResponse>;\n\n/** `PUT /api/projects/:id/vision`. */\nexport const PutVisionRequest = z.object({ contents: z.string().min(1).max(200_000) });\nexport type PutVisionRequest = z.infer<typeof PutVisionRequest>;\n\n// ---------------------------------------------------------------- HTTP shapes\n\n/**\n * `PUT /api/projects/:id/autonomy`. Switching to the software or dark factory requires a GitHub\n * project, a vision file and limits with a daily budget (sent here, or already saved while in\n * a factory mode).\n */\nexport const SetAutonomyModeRequest = z.object({\n mode: AutonomyMode,\n limits: FactoryLimits.optional(),\n tuning: FactoryTuningPatch.optional(),\n});\nexport type SetAutonomyModeRequest = z.infer<typeof SetAutonomyModeRequest>;\n/** What a client sends; `mode` is typed as today's ids (the schema also reads the old one). */\nexport type SetAutonomyModeRequestInit = Omit<z.input<typeof SetAutonomyModeRequest>, \"mode\"> & {\n mode: AutonomyMode;\n};\n\nexport const SetAutonomyModeResponse = z.object({\n projectId: Id,\n mode: AutonomyMode,\n limits: FactoryLimits,\n /** The software and dark factory are experimental. */\n experimental: z.boolean(),\n});\nexport type SetAutonomyModeResponse = z.infer<typeof SetAutonomyModeResponse>;\n\n/**\n * Error code of `POST /api/projects/:id/factory/scout` (\"Run scout now\", → `FactoryStatus`)\n * when no round can start right now (409): not a dark factory, a kill switch is on, the loop is\n * paused, a round is running or no agent slot is free. The message says which, as\n * `ScoutStatus.runNowBlockedBy` does.\n */\nexport const SCOUT_UNAVAILABLE = \"scout_unavailable\";\n\n/** `POST /api/projects/:id/kill-switch` and `POST /api/factory/kill-switch`. */\nexport const KillSwitchRequest = z.object({ on: z.boolean() });\nexport type KillSwitchRequest = z.infer<typeof KillSwitchRequest>;\n\nexport const KillSwitchResponse = z.object({\n on: z.boolean(),\n /** Sessions stopped by turning the switch on. */\n stoppedSessions: z.array(Id),\n});\nexport type KillSwitchResponse = z.infer<typeof KillSwitchResponse>;\n\n/** A work item as the factory panel and its pipeline diagram show it. */\nexport const FactoryWorkItem = z.object({\n id: Id,\n title: z.string(),\n workKey: z.string(),\n issue: GitHubIssueRef.nullable(),\n pr: GitHubPrRef.nullable(),\n score: z.number().nullable(),\n /** The builder session. */\n sessionId: Id.nullable(),\n /** The independent reviewer's session, once there is one. */\n reviewerSessionId: Id.nullable().default(null),\n /** The session working on it right now (the reviewer while reviewing), for the diagram. */\n activeSessionId: Id.nullable().default(null),\n stage: FactoryItemStage,\n step: PipelineStep.default(\"intake\"),\n type: WorkType.nullable().default(null),\n trust: WorkTrust.default(\"trusted\"),\n author: z.string().nullable().default(null),\n source: FactoryItemSource,\n /** Revise rounds so far. */\n attempts: z.int().nonnegative().default(0),\n reason: z.string().nullable(),\n note: z.string().nullable(),\n updatedAt: Timestamp,\n});\nexport type FactoryWorkItem = z.infer<typeof FactoryWorkItem>;\n\n/** Merge-check results of one item with a PR. */\nexport const FactoryMergeChecks = z.object({\n itemId: Id,\n prNumber: z.int().positive(),\n title: z.string(),\n checks: z.array(MergeCheck),\n reviewerProvider: ProviderId.nullable(),\n reviewerNote: z.string().nullable(),\n verdict: ReviewVerdict.shape.verdict.nullable(),\n});\nexport type FactoryMergeChecks = z.infer<typeof FactoryMergeChecks>;\n\n/** `GET /api/projects/:id/factory`: everything the factory panel shows. */\nexport const FactoryStatus = z.object({\n projectId: Id,\n mode: AutonomyMode,\n experimental: z.boolean(),\n loopState: FactoryLoopState,\n pausedReason: z.string().nullable(),\n /** The project's switch; `globalKillSwitch` stops every project. */\n killSwitch: z.boolean(),\n globalKillSwitch: z.boolean(),\n limits: FactoryLimits,\n tuning: FactoryTuning,\n spendToday: z.object({ tokens: z.int().nonnegative(), usd: z.number().nonnegative() }),\n mergesToday: z.int().nonnegative(),\n consecutiveFailures: z.int().nonnegative(),\n activeSessions: z.int().nonnegative(),\n /** Waiting: being classified (`candidate`) or for a free agent (`backlog`). */\n backlog: z.array(FactoryWorkItem),\n inProgress: z.array(FactoryWorkItem),\n mergeChecks: z.array(FactoryMergeChecks),\n /** Merged, reverted, failed, rejected and escalated items, newest first. */\n recent: z.array(FactoryWorkItem),\n /** Issues by untrusted authors, newest first; nothing runs on them until let in. */\n ignored: z.array(FactoryWorkItem).default([]),\n /** The account CodeDen uses on GitHub (always trusted); null when unknown. */\n githubLogin: z.string().nullable().default(null),\n /** The dark factory's scout; null in the software factory. */\n scout: ScoutStatus.nullable().default(null),\n visionExists: z.boolean(),\n lastDigest: FactoryDigest.nullable(),\n lastTickAt: Timestamp.nullable(),\n});\nexport type FactoryStatus = z.infer<typeof FactoryStatus>;\n\n/** `GET /api/projects/:id/factory/items/:itemId`. */\nexport const FactoryItemResponse = z.object({ item: FactoryItem });\nexport type FactoryItemResponse = z.infer<typeof FactoryItemResponse>;\n\n/**\n * `factory_allow_large_change`: the PM lets an item that failed only the size check merge\n * after all, because the work can't be split. The item goes back to verifying.\n */\nexport const FactoryAllowLargeChangeRequest = z.object({\n itemId: Id,\n reason: z.string().trim().min(1).max(500),\n});\nexport type FactoryAllowLargeChangeRequest = z.infer<typeof FactoryAllowLargeChangeRequest>;\n\n// ---------------------------------------------------------------- events\n\n/** Payloads of the factory's persisted events (projected into `factory_*` tables). */\nexport const FACTORY_EVENT_PAYLOADS = {\n \"factory.loop.updated\": z.object({ loop: FactoryLoop }),\n \"factory.item.updated\": z.object({ item: FactoryItem }),\n \"factory.digest.created\": z.object({ digest: FactoryDigest }),\n} as const;\n","import { z } from \"zod\";\nimport { GitHubIssueRef, GitHubPrRef, Id, Timestamp } from \"./common\";\n\n/**\n * GitHub issue and pull request flow (§9): projections synced from GitHub, the events the\n * sync emits, and the HTTP shapes of `/api/projects/:id/github/*`, `/api/prs/:id` and\n * `/api/sessions/:id/github`. Local-only projects never have any of this.\n */\n\n// ---------------------------------------------------------------- connection\n\n/** Where the GitHub token came from: `gh auth token` at runtime, or the OS keychain. */\nexport const GithubTokenSource = z.enum([\"gh\", \"keychain\"]);\nexport type GithubTokenSource = z.infer<typeof GithubTokenSource>;\n\n/** Whether CodeDen can reach GitHub. The token itself never leaves the server. */\nexport const GithubConnection = z.object({\n connected: z.boolean(),\n source: GithubTokenSource.nullable(),\n /** The authenticated user, once known. */\n login: z.string().nullable(),\n /** Why it is not connected, e.g. \"Run `gh auth login`\". */\n message: z.string().nullable(),\n});\nexport type GithubConnection = z.infer<typeof GithubConnection>;\n\n/** Sync state of one GitHub project. */\nexport const GithubSyncStatus = z.object({\n projectId: Id,\n lastSyncAt: Timestamp.nullable(),\n lastError: z.string().nullable(),\n /** Milliseconds between polls right now (faster while sessions have open PRs). */\n intervalMs: z.int().nonnegative(),\n nextSyncAt: Timestamp.nullable(),\n});\nexport type GithubSyncStatus = z.infer<typeof GithubSyncStatus>;\n\n// ---------------------------------------------------------------- entities\n\n/** One issue (pull requests excluded), as projected into `github_issues`. */\nexport const GithubIssue = z.object({\n projectId: Id,\n number: z.int().positive(),\n title: z.string(),\n state: z.enum([\"open\", \"closed\"]),\n url: z.url(),\n labels: z.array(z.string()),\n author: z.string().nullable(),\n body: z.string().nullable(),\n comments: z.int().nonnegative(),\n createdAt: Timestamp.nullable(),\n updatedAt: Timestamp,\n closedAt: Timestamp.nullable(),\n /** CodeDen sessions working on this issue (from each session's `issue`). */\n sessionIds: z.array(Id).default([]),\n});\nexport type GithubIssue = z.infer<typeof GithubIssue>;\n\n/** Combined state of a PR's head commit checks and commit statuses. `none`: no checks. */\nexport const ChecksState = z.enum([\"none\", \"pending\", \"success\", \"failure\"]);\nexport type ChecksState = z.infer<typeof ChecksState>;\n\n/** One check run or commit status on a PR's head commit. */\nexport const GithubCheck = z.object({\n name: z.string(),\n /** `queued`, `in_progress`, `completed` (check runs) or `pending`/`completed` (statuses). */\n status: z.string(),\n /** `success`, `failure`, `neutral`, `skipped`, `cancelled`, `timed_out`, ... once completed. */\n conclusion: z.string().nullable(),\n url: z.string().nullable(),\n});\nexport type GithubCheck = z.infer<typeof GithubCheck>;\n\nexport const GithubChecksSummary = z.object({\n state: ChecksState,\n total: z.int().nonnegative(),\n passed: z.int().nonnegative(),\n failed: z.int().nonnegative(),\n pending: z.int().nonnegative(),\n checks: z.array(GithubCheck),\n});\nexport type GithubChecksSummary = z.infer<typeof GithubChecksSummary>;\n\n/** The PR's review decision (`none` when the repo needs no reviews and none was given). */\nexport const ReviewDecision = z.enum([\"none\", \"review_required\", \"approved\", \"changes_requested\"]);\nexport type ReviewDecision = z.infer<typeof ReviewDecision>;\n\n/**\n * How the author of a review or comment relates to the repository: GitHub's\n * `CommentAuthorAssociation`, lower-cased. `owner`, `member` (of the owning organization) and\n * `collaborator` have write access; anyone else can still review a public repository's PRs.\n */\nexport const GithubAuthorAssociation = z.enum([\n \"owner\",\n \"member\",\n \"collaborator\",\n \"contributor\",\n \"first_time_contributor\",\n \"first_timer\",\n \"mannequin\",\n \"none\",\n]);\nexport type GithubAuthorAssociation = z.infer<typeof GithubAuthorAssociation>;\n\nexport const GithubReview = z.object({\n id: z.string(),\n author: z.string().nullable(),\n /**\n * The author's relation to the repository. Absent on reviews synced before it was tracked,\n * which count as from someone without write access.\n */\n authorAssociation: GithubAuthorAssociation.optional(),\n state: z.enum([\"approved\", \"changes_requested\", \"commented\", \"dismissed\", \"pending\"]),\n body: z.string(),\n submittedAt: Timestamp.nullable(),\n url: z.string().nullable(),\n});\nexport type GithubReview = z.infer<typeof GithubReview>;\n\nexport const Mergeable = z.enum([\"mergeable\", \"conflicting\", \"unknown\"]);\nexport type Mergeable = z.infer<typeof Mergeable>;\n\n/** One pull request, as projected into `github_prs`. */\nexport const GithubPr = z.object({\n /** `<projectId>:<number>`, the id used by `/api/prs/:id`. */\n id: z.string().min(1),\n projectId: Id,\n number: z.int().positive(),\n title: z.string(),\n state: GitHubPrRef.shape.state,\n url: z.url(),\n author: z.string().nullable(),\n headBranch: z.string(),\n baseBranch: z.string(),\n headSha: z.string().nullable(),\n checks: GithubChecksSummary,\n reviewDecision: ReviewDecision,\n /** Latest reviews, oldest first (up to 20). */\n reviews: z.array(GithubReview),\n mergeable: Mergeable,\n /** Issues the PR closes (`Fixes #N` and linked issues). */\n linkedIssues: z.array(z.int().positive()),\n /**\n * Pending review requests: user logins and team slugs (`org/team`), sorted. Absent on rows\n * synced before it was tracked, which tells the sync not to treat every request as new.\n */\n requestedReviewers: z.array(z.string()).optional(),\n /** Latest commits on the PR (up to 50), oldest first. */\n commits: z.array(z.object({ sha: z.string(), message: z.string() })),\n /** The CodeDen session that owns the PR (created it, or works on its head branch). */\n sessionId: Id.nullable(),\n createdAt: Timestamp.nullable(),\n updatedAt: Timestamp,\n mergedAt: Timestamp.nullable(),\n closedAt: Timestamp.nullable(),\n});\nexport type GithubPr = z.infer<typeof GithubPr>;\n\n/** `/api/prs/:id`: the projection plus live details. */\nexport const GithubPrDetails = GithubPr.extend({\n body: z.string(),\n additions: z.int().nonnegative(),\n deletions: z.int().nonnegative(),\n files: z.array(\n z.object({\n path: z.string(),\n status: z.string(),\n additions: z.int().nonnegative(),\n deletions: z.int().nonnegative(),\n }),\n ),\n});\nexport type GithubPrDetails = z.infer<typeof GithubPrDetails>;\n\n/** Build the `/api/prs/:id` id of a PR. */\nexport function githubPrId(projectId: string, number: number): string {\n return `${projectId}:${number}`;\n}\n\n/** Parse a `/api/prs/:id` id; null when malformed. */\nexport function parseGithubPrId(id: string): { projectId: string; number: number } | null {\n const at = id.lastIndexOf(\":\");\n if (at <= 0) return null;\n const number = Number(id.slice(at + 1));\n if (!Number.isInteger(number) || number <= 0) return null;\n return { projectId: id.slice(0, at), number };\n}\n\n// ---------------------------------------------------------------- events\n\nconst issuePayload = { issue: GithubIssue };\n\n/** A new comment on an issue, as carried by `issue.commented`. */\nexport const GithubNewComment = z.object({\n id: z.int(),\n author: z.string().nullable(),\n body: z.string(),\n createdAt: Timestamp,\n url: z.url(),\n /** Posted by CodeDen itself (carries its hidden marker); never triggers automations. */\n fromCodeden: z.boolean(),\n});\nexport type GithubNewComment = z.infer<typeof GithubNewComment>;\nconst prPayload = { pr: GithubPr };\n\n/**\n * Domain events from GitHub sync (§9, §10 triggers). Each carries the full projection row, so\n * `github_issues` / `github_prs` can be rebuilt from the log. `github.synced` is the silent\n * first import of a project (no notices or automations fire for it).\n */\nexport const GITHUB_EVENT_PAYLOADS = {\n \"github.synced\": z.object({\n projectId: Id,\n issues: z.array(GithubIssue),\n prs: z.array(GithubPr),\n }),\n \"issue.opened\": z.object(issuePayload),\n \"issue.labeled\": z.object({ ...issuePayload, added: z.array(z.string()) }),\n /** Title, body, state or label removal changed. `changes` names the fields. */\n \"issue.updated\": z.object({ ...issuePayload, changes: z.array(z.string()) }),\n /**\n * The issue's comment count went up. `comments` are the new comments, oldest first (up to 10;\n * empty when they could not be read).\n */\n \"issue.commented\": z.object({ ...issuePayload, comments: z.array(GithubNewComment) }),\n \"pr.opened\": z.object(prPayload),\n \"pr.updated\": z.object({ ...prPayload, changes: z.array(z.string()) }),\n /** Reviews were requested from `reviewers` (logins or `org/team`) that were not before. */\n \"pr.review_requested\": z.object({ ...prPayload, reviewers: z.array(z.string()) }),\n \"pr.checks_passed\": z.object(prPayload),\n \"pr.checks_failed\": z.object(prPayload),\n \"pr.merged\": z.object(prPayload),\n \"pr.closed\": z.object(prPayload),\n /**\n * A new review. `viewer` is the login of the GitHub account CodeDen read it with (GraphQL\n * `viewer`, answered in the same request), so trusting \"the account CodeDen uses\" follows the\n * credential actually used. Null when GitHub didn't say; absent on events from before it was\n * tracked. Either way no account counts as CodeDen's own.\n */\n \"review.submitted\": z.object({\n ...prPayload,\n review: GithubReview,\n viewer: z.string().nullable().optional(),\n }),\n} as const;\nexport type GithubEventType = keyof typeof GITHUB_EVENT_PAYLOADS;\nexport const GITHUB_EVENT_TYPES = Object.keys(GITHUB_EVENT_PAYLOADS) as GithubEventType[];\n\n// ---------------------------------------------------------------- HTTP shapes\n\nexport const GithubListQuery = z.object({\n state: z.enum([\"open\", \"closed\", \"all\"]).default(\"open\"),\n limit: z.coerce.number().int().min(1).max(500).default(100),\n});\nexport type GithubListQuery = z.infer<typeof GithubListQuery>;\n\nexport const GithubIssuesResponse = z.object({\n connection: GithubConnection,\n sync: GithubSyncStatus.nullable(),\n issues: z.array(GithubIssue),\n});\nexport type GithubIssuesResponse = z.infer<typeof GithubIssuesResponse>;\n\nexport const GithubPrsResponse = z.object({\n connection: GithubConnection,\n sync: GithubSyncStatus.nullable(),\n prs: z.array(GithubPr),\n});\nexport type GithubPrsResponse = z.infer<typeof GithubPrsResponse>;\n\nexport const CreateGithubIssueRequest = z.object({\n title: z.string().min(1).max(256),\n body: z.string().max(65_000).default(\"\"),\n labels: z.array(z.string().min(1)).max(20).default([]),\n});\nexport type CreateGithubIssueRequest = z.infer<typeof CreateGithubIssueRequest>;\n\nexport const GithubCommentRequest = z.object({ body: z.string().min(1).max(65_000) });\nexport type GithubCommentRequest = z.infer<typeof GithubCommentRequest>;\n\nexport const GithubCommentResponse = z.object({ id: z.int(), url: z.url() });\nexport type GithubCommentResponse = z.infer<typeof GithubCommentResponse>;\n\nexport const GithubLabelRequest = z.object({\n add: z.array(z.string().min(1)).max(20).default([]),\n remove: z.array(z.string().min(1)).max(20).default([]),\n});\nexport type GithubLabelRequest = z.infer<typeof GithubLabelRequest>;\n\nexport const MergePrRequest = z.object({\n method: z.enum([\"squash\", \"merge\", \"rebase\"]).default(\"squash\"),\n /** Only merge when the head is still this commit. */\n sha: z.string().optional(),\n commitTitle: z.string().max(256).optional(),\n commitMessage: z.string().max(65_000).optional(),\n});\nexport type MergePrRequest = z.infer<typeof MergePrRequest>;\n\nexport const MergePrResponse = z.object({ merged: z.boolean(), sha: z.string().nullable() });\nexport type MergePrResponse = z.infer<typeof MergePrResponse>;\n\n/** A comment on an issue or PR conversation. */\nexport const GithubIssueComment = z.object({\n id: z.int(),\n author: z.string().nullable(),\n body: z.string(),\n createdAt: Timestamp,\n url: z.url(),\n});\nexport type GithubIssueComment = z.infer<typeof GithubIssueComment>;\n\n/** An issue with its latest comments (up to 20, oldest first), for triage and briefs. */\nexport const GithubIssueDetails = GithubIssue.extend({\n recentComments: z.array(GithubIssueComment),\n});\nexport type GithubIssueDetails = z.infer<typeof GithubIssueDetails>;\n\n/** Issue triage classes (§10): `ready` accepts the issue, the rest decline or defer it. */\nexport const TriageDecision = z.enum([\n \"ready\",\n \"needs_info\",\n \"unsafe\",\n \"out_of_scope\",\n \"duplicate\",\n]);\nexport type TriageDecision = z.infer<typeof TriageDecision>;\n\n/** Apply a triage decision: labels, an optional comment, optionally close the issue. */\nexport const TriageIssueRequest = z.object({\n decision: TriageDecision,\n labels: z.array(z.string().min(1)).max(20).default([]),\n removeLabels: z.array(z.string().min(1)).max(20).default([]),\n comment: z.string().min(1).max(65_000).optional(),\n /** Close the issue (as \"not planned\" unless the decision is `ready`). */\n close: z.boolean().default(false),\n});\nexport type TriageIssueRequest = z.infer<typeof TriageIssueRequest>;\n\nexport const TriageIssueResult = z.object({\n issue: GithubIssue,\n decision: TriageDecision,\n commentUrl: z.url().nullable(),\n closed: z.boolean(),\n});\nexport type TriageIssueResult = z.infer<typeof TriageIssueResult>;\n\n/** `/api/sessions/:id/github`: the session's issue and PR with live status. */\nexport const SessionGithubResponse = z.object({\n connection: GithubConnection,\n issue: GitHubIssueRef.nullable(),\n pr: GithubPr.nullable(),\n});\nexport type SessionGithubResponse = z.infer<typeof SessionGithubResponse>;\n","import { z } from \"zod\";\nimport { GitHubIssueRef, GitHubPrRef, Id, JsonValue, Timestamp } from \"./common\";\nimport { InboxItemKind, InboxItemStatus } from \"./entities/inbox\";\nimport { AutonomyMode } from \"./factory\";\nimport { ConflictDecision, ScheduledRun, StartedBy, WorkKey, WorkSummary } from \"./work\";\n\n/**\n * Orchestration (§8): typed notices that wake the PM and the orchestrator, the status digest\n * injected on every wake, the role sessions and persisted conflicts. Notices are structured\n * data all the way to the UI, which renders them as cards; they are never parsed from text.\n */\n\n/** Who a notice is for: a project's PM or the orchestrator. */\nexport const NoticeTarget = z.enum([\"pm\", \"orchestrator\"]);\nexport type NoticeTarget = z.infer<typeof NoticeTarget>;\n\n/** Kinds of notices (§8.2 step 4). */\nexport const NoticeType = z.enum([\n \"session.finished\",\n \"session.needs_input\",\n \"session.failed\",\n \"pr.opened\",\n \"pr.checks_failed\",\n \"pr.checks_passed\",\n \"pr.merged\",\n \"review.submitted\",\n \"issue.opened\",\n \"automation.skipped\",\n \"conflict\",\n \"pm.message\",\n \"orchestrator.message\",\n \"factory.update\",\n \"reminder\",\n]);\nexport type NoticeType = z.infer<typeof NoticeType>;\n\nconst noticeBase = {\n id: Id,\n projectId: Id.nullable(),\n target: NoticeTarget,\n /** Session the notice is about, when there is one. */\n sessionId: Id.nullable(),\n /** One line for cards and the wake summary. */\n title: z.string(),\n createdAt: Timestamp,\n /** Set when a wake delivered it to its target (or it was shown in a digest). */\n deliveredAt: Timestamp.nullable(),\n /**\n * Whether it wakes its target (§8.2); a routine notice only rides along with the target's\n * next turn. Absent on notices stored before it was recorded.\n */\n wake: z.boolean().optional(),\n /**\n * Not delivered before this time: a wake-up the PM or the orchestrator scheduled for itself\n * (`schedule_wakeup`). Absent or null: deliverable at once.\n */\n notBefore: Timestamp.nullable().optional(),\n};\n\n/** The work a session notice is about. */\nconst workRef = {\n sessionId: Id,\n workKey: WorkKey,\n purpose: z.string(),\n startedBy: StartedBy,\n};\n\n/** A typed notice. `data` is specific to `type`. */\nexport const Notice = z.discriminatedUnion(\"type\", [\n z.object({\n ...noticeBase,\n type: z.literal(\"session.finished\"),\n data: z.object({\n ...workRef,\n /** The agent's `finish` summary, else its final message (start and last paragraph). */\n summary: z.string().nullable(),\n outcome: z.string().nullable(),\n }),\n }),\n z.object({\n ...noticeBase,\n type: z.literal(\"session.needs_input\"),\n data: z.object({ ...workRef, inboxItemId: Id, kind: InboxItemKind, question: z.string() }),\n }),\n z.object({\n ...noticeBase,\n type: z.literal(\"session.failed\"),\n data: z.object({ ...workRef, error: z.string() }),\n }),\n z.object({\n ...noticeBase,\n type: z.literal(\"pr.opened\"),\n data: z.object({ sessionId: Id.nullable(), pr: GitHubPrRef }),\n }),\n z.object({\n ...noticeBase,\n type: z.literal(\"pr.checks_failed\"),\n data: z.object({\n sessionId: Id.nullable(),\n pr: GitHubPrRef,\n failedChecks: z.array(z.string()),\n }),\n }),\n z.object({\n ...noticeBase,\n type: z.literal(\"pr.checks_passed\"),\n data: z.object({ sessionId: Id.nullable(), pr: GitHubPrRef }),\n }),\n z.object({\n ...noticeBase,\n type: z.literal(\"pr.merged\"),\n data: z.object({\n sessionId: Id.nullable(),\n pr: GitHubPrRef,\n /** Issues the PR closes. */\n linkedIssues: z.array(z.int().positive()),\n }),\n }),\n z.object({\n ...noticeBase,\n type: z.literal(\"review.submitted\"),\n data: z.object({\n sessionId: Id.nullable(),\n pr: GitHubPrRef,\n reviewer: z.string().nullable(),\n state: z.enum([\"approved\", \"changes_requested\", \"commented\", \"dismissed\", \"pending\"]),\n /** Start of the review body; empty for an untrusted review. */\n body: z.string(),\n /**\n * The reviewer has no write access to the repository and is not a trusted author: the\n * body is left out, and the review is no instruction to anyone. Absent on trusted\n * reviews (and on notices from before it was tracked).\n */\n untrusted: z.boolean().optional(),\n }),\n }),\n z.object({\n ...noticeBase,\n type: z.literal(\"issue.opened\"),\n data: z.object({\n issue: GitHubIssueRef,\n author: z.string().nullable(),\n labels: z.array(z.string()),\n }),\n }),\n z.object({\n ...noticeBase,\n type: z.literal(\"automation.skipped\"),\n data: z.object({\n automationRunId: Id,\n automationId: Id,\n workKey: WorkKey,\n purpose: z.string(),\n reason: z.string(),\n }),\n }),\n z.object({\n ...noticeBase,\n type: z.literal(\"conflict\"),\n data: z.object({\n conflictId: Id,\n workKey: WorkKey,\n purpose: z.string(),\n requestedBy: StartedBy,\n existing: z.array(WorkSummary),\n }),\n }),\n z.object({\n ...noticeBase,\n type: z.literal(\"pm.message\"),\n data: z.object({\n fromSessionId: Id,\n text: z.string(),\n /** Informational messages never wake the orchestrator; they show in its next digest. */\n informational: z.boolean(),\n }),\n }),\n /**\n * A message from the orchestrator to a PM that the loop guard held back (§8.2): the two had\n * already exchanged several automatic messages without the user stepping in. It reaches the\n * PM with its next wake, at the latest once the guard's window allows another message.\n */\n z.object({\n ...noticeBase,\n type: z.literal(\"orchestrator.message\"),\n data: z.object({\n /** The orchestrator session that sent it, when known. */\n fromSessionId: Id.nullable(),\n /** The message as the orchestrator wrote it (an `ask_pm` question carries its marker). */\n text: z.string(),\n }),\n }),\n z.object({\n ...noticeBase,\n type: z.literal(\"factory.update\"),\n data: z.object({\n /** What happened in the factory loop (§10.1). */\n event: z.enum([\n \"triage_needed\",\n \"digest\",\n \"paused\",\n \"escalated\",\n \"regression\",\n \"merged\",\n \"failed\",\n \"ready\",\n ]),\n /** Instructions (for the PM) or a summary (for the orchestrator). */\n text: z.string(),\n itemIds: z.array(Id).default([]),\n }),\n }),\n /**\n * A wake-up the PM or the orchestrator scheduled for itself (`schedule_wakeup`), due at\n * `notBefore`: it wakes them then with their note, so they follow up without the user.\n */\n z.object({\n ...noticeBase,\n type: z.literal(\"reminder\"),\n data: z.object({\n /** What to do when it fires, as they wrote it. */\n note: z.string(),\n /** The role session that scheduled it. */\n requestedBy: Id.nullable(),\n }),\n }),\n]);\nexport type Notice = z.infer<typeof Notice>;\nexport type NoticeOf<T extends NoticeType> = Extract<Notice, { type: T }>;\n\n/** `notice` item `code` used for the batch of notices shown at the start of a wake turn. */\nexport const NOTICE_BATCH_CODE = \"orchestration_notices\";\n\n/** `data` of a `notice` item with `code: \"orchestration_notices\"` (rendered as cards). */\nexport const NoticeBatchData = z.object({\n notices: z.array(Notice),\n});\nexport type NoticeBatchData = z.infer<typeof NoticeBatchData>;\n\n// ---------------------------------------------------------------- status digest (§8.4)\n\n/** A recent outcome of agent work, for digests. */\nexport const RecentOutcome = z.object({\n sessionId: Id,\n workKey: WorkKey,\n purpose: z.string(),\n outcome: z.enum([\"finished\", \"failed\", \"stopped\"]),\n summary: z.string().nullable(),\n at: Timestamp,\n});\nexport type RecentOutcome = z.infer<typeof RecentOutcome>;\n\n/** Everything a PM needs to know about its project, without spending a tool call. */\nexport const ProjectStatus = z.object({\n project: z.object({\n id: Id,\n name: z.string(),\n kind: z.enum([\"github\", \"local\"]),\n /**\n * The project's autonomy mode: tells the PM who merges pull requests (the user in manual and\n * assisted, the factory loop in the software and dark factory).\n */\n mode: AutonomyMode,\n }),\n /** Agent sessions and automation runs that are starting, running or waiting. */\n running: z.array(WorkSummary),\n /** Work queued behind other work (§8.4 `wait`). */\n queued: z.array(WorkSummary),\n /** Next scheduled automation runs. */\n scheduled: z.array(ScheduledRun),\n inbox: z.object({\n open: z.int().nonnegative(),\n items: z.array(\n z.object({ id: Id, kind: InboxItemKind, title: z.string(), sessionId: Id.nullable() }),\n ),\n }),\n /** Finishes and failures of the last 24 hours, newest first. */\n recent: z.array(RecentOutcome),\n});\nexport type ProjectStatus = z.infer<typeof ProjectStatus>;\n\n/** The orchestrator's view: every project rolled up (`get_overview`). */\nexport const Overview = z.object({\n generatedAt: Timestamp,\n projects: z.array(ProjectStatus),\n /** Work keys running in more than one project at once. */\n sharedWork: z.array(z.object({ workKey: WorkKey, projectIds: z.array(Id) })),\n /** PM messages marked informational that the orchestrator has not seen yet. */\n pmMessages: z.array(z.object({ projectId: Id.nullable(), text: z.string(), at: Timestamp })),\n});\nexport type Overview = z.infer<typeof Overview>;\n\n// ---------------------------------------------------------------- role sessions and conflicts\n\n/** The long-lived role sessions (§8.1): the orchestrator and one PM per project. */\nexport const RoleSessionsRef = z.object({\n orchestrator: Id.nullable(),\n /** PM session id by project id. */\n pms: z.record(z.string(), Id),\n});\nexport type RoleSessionsRef = z.infer<typeof RoleSessionsRef>;\n\n/**\n * A start request that matched running work, persisted as an inbox item of kind `conflict`\n * (`id` is the inbox item id). Resolved with `wait`, `skip`, `join` or `force` (§8.4).\n */\nexport const ConflictRecord = z.object({\n id: Id,\n projectId: Id.nullable(),\n request: z.object({ purpose: z.string(), workKey: WorkKey, startedBy: StartedBy }),\n existing: z.array(WorkSummary).min(1),\n /** The original `StartSessionRequest`, retried with the decision. */\n start: JsonValue,\n status: InboxItemStatus,\n resolution: ConflictDecision.nullable(),\n /** The `StartSessionResponse` of the retried start. */\n outcome: JsonValue.nullable(),\n createdAt: Timestamp,\n resolvedAt: Timestamp.nullable(),\n});\nexport type ConflictRecord = z.infer<typeof ConflictRecord>;\n","import { z } from \"zod\";\nimport { Timestamp } from \"./common\";\n\n/**\n * `settings.updates.mode` (§16): `off` never asks the registry; `notify` checks and offers a\n * one-click update; `auto` also downloads a new version in the background so it starts on the\n * next launch (or right away with \"Restart now\").\n */\nexport const UpdateMode = z.enum([\"off\", \"notify\", \"auto\"]);\nexport type UpdateMode = z.infer<typeof UpdateMode>;\n\n/**\n * Where the running CodeDen came from. `packaged`: an npm install (`npx`, global or a\n * side-by-side version in `<home>/app`), which can update itself. `source`: the repository or\n * a workspace build, which never switches versions (pull and rebuild instead). `desktop`: the\n * desktop app, which updates itself from GitHub Releases (the npm path is off; §17).\n */\nexport const InstallSource = z.enum([\"packaged\", \"source\", \"desktop\"]);\nexport type InstallSource = z.infer<typeof InstallSource>;\n\n/**\n * Self-update progress. `installing`: npm is fetching `target` into `<home>/app/<target>`;\n * `installed`: it is ready and starts on the next launch (or with a restart); `restarting`:\n * the server is handing over to `target`; `failed`: see `installError`.\n */\nexport const UpdateState = z.enum([\"idle\", \"installing\", \"installed\", \"restarting\", \"failed\"]);\nexport type UpdateState = z.infer<typeof UpdateState>;\n\n/** A CodeDen version installed side by side in `<home>/app/<version>`. */\nexport const InstalledVersion = z.object({\n version: z.string(),\n /** `<home>/app/current.json` points at it: the launcher starts it. */\n current: z.boolean(),\n /** The CLI entry exists and its package reports this version. */\n valid: z.boolean(),\n});\nexport type InstalledVersion = z.infer<typeof InstalledVersion>;\n\n/**\n * `GET /api/updates` (§16) and the `update` WebSocket message: the npm registry check plus the\n * one-click self-update state. The registry is asked on start and every 6 hours while the\n * mode is not `off`; `?refresh=1` checks again now. Nothing but the package name is sent.\n */\nexport const UpdateStatus = z.object({\n /** The running version. */\n current: z.string(),\n /** Latest published version, null until a check succeeded. */\n latest: z.string().nullable(),\n /** `latest` is newer than `current`. */\n updateAvailable: z.boolean(),\n /** The mode is not `off` (and `CODEDEN_UPDATE_CHECK` is not `0`); when false nothing is fetched. */\n enabled: z.boolean(),\n mode: UpdateMode,\n checkedAt: Timestamp.nullable(),\n /** Why the last check failed (offline, registry error), else null. */\n error: z.string().nullable(),\n /** The manual way to update, e.g. `npm i -g codeden@latest`. */\n command: z.string(),\n source: InstallSource,\n state: UpdateState,\n /** The version being installed, installed and waiting for a restart, or restarting into. */\n target: z.string().nullable(),\n /** The latest npm output line while installing. */\n progress: z.string().nullable(),\n /** Why the last install, switch or restart failed. */\n installError: z.string().nullable(),\n /** This server can restart itself into another version (started by the `codeden` CLI). */\n canRestart: z.boolean(),\n /** What to run to restart by hand when it can't, e.g. `npx codeden`. */\n restartCommand: z.string(),\n /** Versions in `<home>/app`, newest first. */\n installed: z.array(InstalledVersion),\n /** The version \"Roll back\" would start (the previous one, or the copy you launched). */\n rollbackTo: z.string().nullable(),\n /** \"Roll back\" is possible (a previous version is recorded). */\n canRollback: z.boolean(),\n /** Set when the launcher could not start the pinned version and fell back. */\n warning: z.string().nullable(),\n});\nexport type UpdateStatus = z.infer<typeof UpdateStatus>;\n\n/** `POST /api/updates/install`: install `version` (default: the latest) and restart into it. */\nexport const UpdateInstallRequest = z.object({\n version: z.string().min(1).optional(),\n /** Restart once installed (default true); false leaves it for the next launch. */\n restart: z.boolean().optional(),\n});\nexport type UpdateInstallRequest = z.infer<typeof UpdateInstallRequest>;\n\n/** `GET /api/updates/notes?version=`: release notes for \"What's new\". */\nexport const ReleaseNotes = z.object({\n version: z.string(),\n /** Markdown from the GitHub Release body or the CHANGELOG section; null when unreachable. */\n body: z.string().nullable(),\n /** Where to read them in the browser. */\n url: z.string(),\n});\nexport type ReleaseNotes = z.infer<typeof ReleaseNotes>;\n\n/**\n * `<home>/app/current.json`: which side-by-side version the `codeden` launcher starts. Written\n * by the server or `codeden update`; read (without zod, on the hot path) by the launcher in\n * `apps/cli/src/launcher.ts`, which must accept everything this schema accepts.\n */\nexport const AppPointer = z.object({\n version: z.string().min(1),\n /** The version that ran before the switch (\"Roll back\" target), null when unknown. */\n previous: z.string().nullable(),\n updatedAt: Timestamp,\n});\nexport type AppPointer = z.infer<typeof AppPointer>;\n\n/** True when version `a` is newer than `b` (`x.y.z`, prerelease tags sort before releases). */\nexport function isNewerVersion(a: string, b: string): boolean {\n return compareVersions(a, b) > 0;\n}\n\n/** Compare two `x.y.z[-pre]` versions: negative when `a < b`, 0 when equal, positive when newer. */\nexport function compareVersions(a: string, b: string): number {\n const parse = (v: string) => {\n const trimmed = v.trim().replace(/^v/, \"\");\n const dash = trimmed.indexOf(\"-\");\n const core = dash === -1 ? trimmed : trimmed.slice(0, dash);\n const pre = dash === -1 ? \"\" : trimmed.slice(dash + 1);\n return { nums: core.split(\".\").map((n) => Number.parseInt(n, 10) || 0), pre };\n };\n const x = parse(a);\n const y = parse(b);\n for (let i = 0; i < 3; i++) {\n const d = (x.nums[i] ?? 0) - (y.nums[i] ?? 0);\n if (d !== 0) return d;\n }\n if (x.pre === y.pre) return 0;\n if (!x.pre) return 1; // release beats prerelease\n if (!y.pre) return -1;\n return comparePrerelease(x.pre, y.pre);\n}\n\n/** Dot-separated prerelease identifiers: numeric ones compare as numbers and sort first. */\nfunction comparePrerelease(a: string, b: string): number {\n const xs = a.split(\".\");\n const ys = b.split(\".\");\n for (let i = 0; i < Math.max(xs.length, ys.length); i++) {\n const x = xs[i];\n const y = ys[i];\n if (x === undefined) return -1;\n if (y === undefined) return 1;\n const xn = /^\\d+$/.test(x);\n const yn = /^\\d+$/.test(y);\n if (xn && yn) {\n const d = Number(x) - Number(y);\n if (d !== 0) return d;\n } else if (xn !== yn) {\n return xn ? -1 : 1;\n } else if (x !== y) {\n return x < y ? -1 : 1;\n }\n }\n return 0;\n}\n","import { z } from \"zod\";\n\n/**\n * Voice engines on the server (§11.3). The browser's speech APIs stay the default; these\n * routes proxy ElevenLabs (text to speech, Scribe) and OpenAI (transcription) with API keys\n * from the OS keychain, so keys never reach the browser, and run local Whisper with a\n * runtime and model downloaded on demand.\n */\n\n/** ElevenLabs MP3 output formats (`codec_sampleRate_bitrate`). */\nexport const TtsOutputFormat = z.enum([\n \"mp3_22050_32\",\n \"mp3_44100_64\",\n \"mp3_44100_128\",\n \"mp3_44100_192\",\n]);\nexport type TtsOutputFormat = z.infer<typeof TtsOutputFormat>;\n\n/**\n * `POST /api/tts`: streams `audio/mpeg`. `voiceId` defaults to\n * `settings.voice.readAloud.voice`, then a stock voice; `modelId` to a low-latency model.\n */\nexport const TtsRequest = z.object({\n text: z.string().min(1).max(5_000),\n voiceId: z.string().min(1).max(100).optional(),\n modelId: z.string().min(1).max(100).optional(),\n outputFormat: TtsOutputFormat.optional(),\n});\nexport type TtsRequest = z.infer<typeof TtsRequest>;\n\n/** One ElevenLabs voice for the voice picker. */\nexport const VoiceInfo = z.object({\n id: z.string(),\n name: z.string(),\n category: z.string().optional(),\n description: z.string().optional(),\n previewUrl: z.string().optional(),\n labels: z.record(z.string(), z.string()).optional(),\n});\nexport type VoiceInfo = z.infer<typeof VoiceInfo>;\n\n/** `GET /api/voice/voices`. */\nexport const VoiceListResponse = z.object({ voices: z.array(VoiceInfo) });\nexport type VoiceListResponse = z.infer<typeof VoiceListResponse>;\n\n/** Engines that transcribe on the server: the cloud engines and local Whisper. */\nexport const SttEngine = z.enum([\"elevenlabs\", \"openai\", \"local\"]);\nexport type SttEngine = z.infer<typeof SttEngine>;\n\n/**\n * `POST /api/stt?engine=&language=`: the body is the recorded audio (raw bytes with an\n * `audio/*` content type, or multipart with a `file` field), up to 25 MB. `engine` defaults\n * to `settings.voice.dictation.engine` (when that is `browser`, ElevenLabs). The `local`\n * engine only takes WAV, 16-bit PCM, mono at `LOCAL_STT_SAMPLE_RATE`, at most\n * `LOCAL_STT_MAX_SECONDS` long (the UI converts the recording before uploading).\n */\nexport const SttQuery = z.object({\n engine: SttEngine.optional(),\n /** ISO 639-1 hint, e.g. `en`. */\n language: z.string().min(2).max(10).optional(),\n});\nexport type SttQuery = z.infer<typeof SttQuery>;\n\nexport const SttResponse = z.object({\n text: z.string(),\n language: z.string().nullable(),\n engine: SttEngine,\n /** How long the server spent transcribing, in milliseconds (local engine). */\n elapsedMs: z.number().nonnegative().optional(),\n});\nexport type SttResponse = z.infer<typeof SttResponse>;\n\n// ---------------------------------------------------------------- local Whisper (§11.3)\n\n/**\n * Dictation engines (`settings.voice.dictation.engine`): the browser's speech recognition,\n * a cloud engine through the server, or `local` Whisper running on the CodeDen server.\n */\nexport const DictationEngine = z.enum([\"browser\", \"elevenlabs\", \"openai\", \"local\"]);\nexport type DictationEngine = z.infer<typeof DictationEngine>;\n\n/**\n * Local Whisper models CodeDen can download. `.en` models are English-only (more accurate\n * for English at the same size); the others detect or take a language.\n */\nexport const WhisperModelId = z.enum([\"tiny\", \"tiny.en\", \"base\", \"base.en\", \"small\", \"small.en\"]);\nexport type WhisperModelId = z.infer<typeof WhisperModelId>;\n\n/** Audio format the local engine accepts: WAV, 16-bit PCM, mono, at this sample rate. */\nexport const LOCAL_STT_SAMPLE_RATE = 16_000;\n/** Longest clip the local engine transcribes in one request, in seconds. */\nexport const LOCAL_STT_MAX_SECONDS = 120;\n\n/**\n * Where one download (the runtime or a model) stands. `missing`: not on disk;\n * `downloading`: in progress (bytes below); `installed`: verified and on disk;\n * `failed`: the last attempt failed (`error`), a retry resumes or restarts it.\n */\nexport const LocalSttDownloadState = z.enum([\"missing\", \"downloading\", \"installed\", \"failed\"]);\nexport type LocalSttDownloadState = z.infer<typeof LocalSttDownloadState>;\n\nconst downloadFields = {\n state: LocalSttDownloadState,\n /** Bytes received so far (while downloading). */\n receivedBytes: z.int().nonnegative(),\n /** Download size in bytes (pinned, so known before the download starts). */\n totalBytes: z.int().nonnegative(),\n /** Size on disk when installed. */\n sizeOnDisk: z.int().nonnegative().nullable(),\n /** Why the last attempt failed. */\n error: z.string().nullable(),\n};\n\n/** The Whisper runtime: a prebuilt native library for this platform, downloaded on demand. */\nexport const LocalSttRuntime = z.object({\n /** Runtime version CodeDen pins. */\n version: z.string(),\n ...downloadFields,\n});\nexport type LocalSttRuntime = z.infer<typeof LocalSttRuntime>;\n\n/** One downloadable model, with a speed and accuracy hint for the picker. */\nexport const LocalSttModel = z.object({\n id: WhisperModelId,\n /** e.g. `Base (English)`. */\n label: z.string(),\n /** Speed and accuracy hint, e.g. `Fast, good accuracy`. */\n hint: z.string(),\n englishOnly: z.boolean(),\n /** The suggested default. */\n recommended: z.boolean(),\n ...downloadFields,\n});\nexport type LocalSttModel = z.infer<typeof LocalSttModel>;\n\n/** `GET /api/voice/local`: the local Whisper engine on this machine. */\nexport const LocalSttStatus = z.object({\n /** False on platforms without a prebuilt runtime (`unsupportedReason` says why). */\n supported: z.boolean(),\n /** `process.platform-process.arch` of the server, e.g. `win32-x64`. */\n platform: z.string(),\n unsupportedReason: z.string().nullable(),\n runtime: LocalSttRuntime,\n models: z.array(LocalSttModel),\n /** Folder holding the models. */\n location: z.string(),\n});\nexport type LocalSttStatus = z.infer<typeof LocalSttStatus>;\n\n/**\n * `POST /api/voice/local/models/:id/download` starts (or joins) the download of the runtime\n * and that model; `DELETE /api/voice/local/models/:id` cancels or deletes it. Both return\n * the new `LocalSttStatus`. The UI polls `GET /api/voice/local` while anything downloads.\n */\nexport const LocalSttModelParams = z.object({ id: WhisperModelId });\nexport type LocalSttModelParams = z.infer<typeof LocalSttModelParams>;\n","import { z } from \"zod\";\nimport { AutonomyLevel, ProviderId, QuietHours, ReasoningEffort } from \"./common\";\nimport { UpdateMode } from \"./updates\";\nimport { DictationEngine, WhisperModelId } from \"./voice-api\";\n\n/** `auto` lets CodeDen pick the first ready provider (Claude, then Codex, then OpenCode). */\nexport const ProviderChoice = z.union([z.literal(\"auto\"), ProviderId]);\nexport type ProviderChoice = z.infer<typeof ProviderChoice>;\n\n/** Image engine choice (§12.5): `auto` picks Codex when logged in, `none` hides the tool. */\nexport const ImageEngineSetting = z.enum([\"auto\", \"codex\", \"gemini\", \"openai\", \"none\"]);\nexport type ImageEngineSetting = z.infer<typeof ImageEngineSetting>;\n\n/**\n * What read-aloud speaks when a turn finishes (§11.3):\n * - `summary`: a spoken TL;DR of at most two short sentences from the utility model (§7.4),\n * or the message's first sentence or two when the model can't produce one.\n * - `full`: the whole final message with code and markdown removed, no model call, capped at\n * `READ_ALOUD_FULL_MAX_CHARS`.\n */\nexport const ReadAloudContent = z.enum([\"summary\", \"full\"]);\nexport type ReadAloudContent = z.infer<typeof ReadAloudContent>;\n\n/** Hard cap on a spoken TL;DR, the model's output included (about 15 seconds of speech). */\nexport const READ_ALOUD_SUMMARY_MAX_CHARS = 220;\n/** Safety cap on `full` read-aloud (roughly five minutes of speech). */\nexport const READ_ALOUD_FULL_MAX_CHARS = 5_000;\n\n/**\n * Cut already-plain text to whole sentences within `maxChars`: as many leading sentences as fit,\n * or the first one cut at a word boundary with an ellipsis when even that is too long.\n */\nexport function speechExcerpt(plain: string, maxChars: number, maxSentences = Infinity): string {\n const text = plain.replace(/\\s+/g, \" \").trim();\n const sentences = text.split(/(?<=[.!?])\\s+/);\n let out = \"\";\n for (const [i, sentence] of sentences.entries()) {\n if (i >= maxSentences) break;\n const next = out ? `${out} ${sentence}` : sentence;\n if (next.length > maxChars) break;\n out = next;\n }\n if (out) return out;\n const cut = text.slice(0, Math.max(0, maxChars - 3));\n const space = cut.lastIndexOf(\" \");\n return `${(space > maxChars / 2 ? cut.slice(0, space) : cut).replace(/[\\s,;:-]+$/, \"\")}...`;\n}\n\n/** Per-project image generation override; unset fields fall back to the global settings. */\nexport const ImageGenerationOverride = z.object({\n engine: ImageEngineSetting.optional(),\n defaultSize: z.string().optional(),\n quality: z.enum([\"auto\", \"low\", \"medium\", \"high\"]).optional(),\n /** Images per day for this project (counted on its own, inside the global cap). */\n dailyCap: z.int().nonnegative().optional(),\n});\nexport type ImageGenerationOverride = z.infer<typeof ImageGenerationOverride>;\n\n/** Default provider/model/effort for one role. */\nexport const RoleDefaults = z.object({\n provider: ProviderChoice.default(\"auto\"),\n model: z.string().nullable().default(null),\n effort: ReasoningEffort.nullable().default(null),\n});\nexport type RoleDefaults = z.infer<typeof RoleDefaults>;\n\n/** A model named by its provider and the provider's model id. */\nexport const ModelRef = z.object({\n provider: ProviderId,\n model: z.string().min(1),\n});\nexport type ModelRef = z.infer<typeof ModelRef>;\n\n/**\n * A model id the user added for a provider that doesn't list it (a new model, or one only\n * exposed through the provider's own config). The id is sent to the provider unchanged.\n */\nexport const CustomModel = z.object({\n id: z.string().trim().min(1).max(200),\n /** Shown instead of the id in the picker. */\n label: z.string().trim().min(1).max(100).optional(),\n});\nexport type CustomModel = z.infer<typeof CustomModel>;\n\n/** A provider's custom models: ids are unique. */\nconst CustomModelList = z\n .array(CustomModel)\n .refine((list) => new Set(list.map((m) => m.id)).size === list.length, {\n message: \"Custom model ids must be unique\",\n });\n\n/**\n * User settings persisted in `<home>/settings.json` (non-secret; API keys live in the OS\n * keychain). Every field has a default, so `Settings.parse({})` yields a complete object and\n * older files keep working as fields are added.\n */\nexport const Settings = z.object({\n schemaVersion: z.literal(1).default(1),\n appearance: z\n .object({\n theme: z.enum([\"system\", \"dark\", \"light\"]).default(\"dark\"),\n })\n .prefault({}),\n /** Default autonomy level (§11.2), overridable per project and session. */\n autonomy: z\n .object({\n default: AutonomyLevel.default(\"auto\"),\n })\n .prefault({}),\n providers: z\n .object({\n orchestrator: RoleDefaults.prefault({}),\n pm: RoleDefaults.prefault({}),\n agent: RoleDefaults.prefault({}),\n })\n .prefault({}),\n /** Small, cheap model for side jobs (§7.4). */\n utilityModel: z\n .object({\n provider: ProviderChoice.default(\"auto\"),\n model: z.string().nullable().default(null),\n jobs: z\n .object({\n followups: z.boolean().default(true),\n /**\n * @deprecated Superseded by `voice.readAloud.content` (§11.3) and no longer read. Kept\n * so settings files written before it was replaced still load.\n */\n readAloudSummary: z.boolean().default(true),\n sessionTitles: z.boolean().default(true),\n noticeSummaries: z.boolean().default(true),\n })\n .prefault({}),\n })\n .prefault({}),\n /** The model picker (§13). */\n models: z\n .object({\n /**\n * Starred models, listed in this order in the picker's Favourites section. Entries whose\n * model a provider no longer lists are kept (it may come back) but not shown.\n */\n favorites: z.array(ModelRef).default([]),\n /**\n * Model ids left out of the picker, by provider id. A hidden model that is still chosen\n * somewhere (a session, a default, an automation) keeps showing there.\n */\n hidden: z.record(ProviderId, z.array(z.string().min(1))).default({}),\n /**\n * Model ids added by the user, by provider id, merged into the picker after the models\n * the provider lists (a listed id wins). Their effort levels are those of the provider's\n * default model, or none when the provider has no effort levels.\n */\n custom: z.record(ProviderId, CustomModelList).default({}),\n })\n .prefault({}),\n /** Follow-up prompt chips (§7.5). */\n followups: z\n .object({\n enabled: z.boolean().default(true),\n /** Send immediately on click instead of filling the composer. */\n sendOnClick: z.boolean().default(false),\n })\n .prefault({}),\n /** Voice (§11.3). */\n voice: z\n .object({\n dictation: z\n .object({\n engine: DictationEngine.default(\"browser\"),\n pushToTalkShortcut: z.string().nullable().default(null),\n /**\n * BCP 47 tag such as `en-US`; null is auto (the browser engine follows the browser\n * language, the server engines detect it). English-only Whisper models ignore it.\n */\n language: z.string().nullable().default(null),\n /** Local Whisper: which downloaded model transcribes (§11.3). */\n local: z\n .object({\n model: WhisperModelId.default(\"base.en\"),\n })\n .prefault({}),\n })\n .prefault({}),\n readAloud: z\n .object({\n enabled: z.boolean().default(false),\n engine: z.enum([\"browser\", \"elevenlabs\"]).default(\"browser\"),\n voice: z.string().nullable().default(null),\n /** What gets read when a turn finishes (§11.3); see `ReadAloudContent`. */\n content: ReadAloudContent.default(\"summary\"),\n /**\n * Start each message with who it's from (\"Orchestrator\", \"<project> project manager\",\n * \"<project>, <session title>\"), built from the session, never by a model.\n */\n announceSpeaker: z.boolean().default(true),\n onlyWhenUnfocused: z.boolean().default(false),\n quietHours: QuietHours.nullable().default(null),\n })\n .prefault({}),\n })\n .prefault({}),\n /** Image generation for every agent (§12.5). */\n imageGeneration: z\n .object({\n /** `auto`: Codex when logged in, else the first engine with a key; `none` hides the tool. */\n engine: ImageEngineSetting.default(\"auto\"),\n defaultSize: z.string().default(\"1024x1024\"),\n quality: z.enum([\"auto\", \"low\", \"medium\", \"high\"]).default(\"auto\"),\n /** Images per day across all projects (0 turns generation off). */\n dailyCap: z.int().nonnegative().default(50),\n /** Overrides by project id. */\n projects: z.record(z.string(), ImageGenerationOverride).default({}),\n })\n .prefault({}),\n notifications: z\n .object({\n toasts: z.boolean().default(true),\n browser: z.boolean().default(false),\n /** A short chime when an agent is blocked on the user (an approval or a question). */\n sound: z.boolean().default(true),\n /**\n * Which inbox categories (`InboxItem.notify`) raise a toast and a desktop notification.\n * Approvals and questions always do while `toasts` / `browser` is on; switched-off\n * categories still land in the inbox. The factory looks after its own activity, so that\n * category is off by default.\n */\n categories: z\n .object({\n needs_you: z.boolean().default(true),\n failure: z.boolean().default(true),\n factory: z.boolean().default(false),\n automation: z.boolean().default(true),\n })\n .prefault({}),\n })\n .prefault({}),\n /** Global factory controls (§10.1). */\n factory: z\n .object({\n /** Stops every project's factory loop and all factory sessions. */\n killSwitch: z.boolean().default(false),\n })\n .prefault({}),\n /**\n * Worktree cleanup (§9). Archiving a session removes its worktree (unless it has uncommitted changes and isn't forced); with `cleanup` on,\n * worktrees of sessions inactive for `afterDays` are removed too, unless the session's pull\n * request is still open or the worktree has uncommitted changes.\n */\n worktrees: z\n .object({\n cleanup: z.boolean().default(true),\n afterDays: z.int().min(1).max(365).default(7),\n })\n .prefault({}),\n /**\n * What CodeDen does by itself for agent sessions the user started (work started by a PM, the\n * orchestrator or an automation is followed up by the PM instead).\n */\n sessions: z\n .object({\n /**\n * Tell the session that owns a pull request when its checks fail, a reviewer requests\n * changes or it gets merge conflicts (once per head commit, at most a few rounds per PR).\n */\n prFeedback: z.boolean().default(true),\n /**\n * Continue an agent session by itself after a turn fails for a passing reason: an\n * overloaded API or dropped connection (after 20 s, 90 s and 5 min, then it gives up) or\n * a usage limit (a minute after it resets). Off: such a turn fails the session as before.\n */\n autoRetry: z.boolean().default(true),\n })\n .prefault({}),\n /** Master switch; individual automations are still off by default (§10). */\n automations: z\n .object({\n enabled: z.boolean().default(true),\n })\n .prefault({}),\n /**\n * Update checks and one-click self-update (§16). Settings saved before `mode` existed had\n * `check: false` to turn checks off; that reads as `mode: \"off\"`.\n */\n updates: z.preprocess(\n (value) =>\n typeof value === \"object\" &&\n value !== null &&\n !(\"mode\" in value) &&\n (value as { check?: unknown }).check === false\n ? { mode: \"off\" }\n : value,\n z\n .object({\n mode: UpdateMode.default(\"notify\"),\n })\n .prefault({}),\n ),\n /** The desktop app (§17). Read by the desktop app only; `npx codeden` ignores it. */\n desktop: z\n .object({\n /** Start CodeDen (in the tray, window hidden) when you log in. */\n launchAtLogin: z.boolean().default(false),\n /** Closing the window keeps CodeDen running in the tray / menu bar; Quit really quits. */\n closeToTray: z.boolean().default(true),\n /** Keep the computer from sleeping while an agent is running. */\n keepAwake: z.boolean().default(true),\n /**\n * Show session browsers as native browser views in the app (§17 Phase 2) instead of the\n * screencast. Applies to browsers opened from then on; off falls back to the screencast.\n */\n nativeBrowser: z.boolean().default(true),\n })\n .prefault({}),\n /** First-run setup (§14): set once the user finishes the detection checklist. */\n setup: z\n .object({\n completed: z.boolean().default(false),\n completedAt: z.iso.datetime().nullable().default(null),\n })\n .prefault({}),\n});\nexport type Settings = z.infer<typeof Settings>;\n/** Settings as accepted on input: any subset, defaults fill the rest. */\nexport type SettingsInput = z.input<typeof Settings>;\n\n/** Recursive partial used for `PATCH /api/settings`; validated by re-parsing the merged result. */\nexport type DeepPartial<T> = T extends readonly unknown[]\n ? T\n : T extends object\n ? { [K in keyof T]?: DeepPartial<T[K]> }\n : T;\nexport type SettingsPatch = DeepPartial<Settings>;\n\n/** Default settings. */\nexport function defaultSettings(): Settings {\n return Settings.parse({});\n}\n","import { z } from \"zod\";\nimport {\n type AgentEvent,\n ItemCompletedEvent,\n ItemDeltaEvent,\n ItemStartedEvent,\n ItemUpdatedEvent,\n SessionUpdatedEvent,\n ThreadStartedEvent,\n TurnCompletedEvent,\n TurnFailedEvent,\n TurnInterruptedEvent,\n TurnStartedEvent,\n UsageUpdatedEvent,\n} from \"./agent-events\";\nimport { Id, Timestamp } from \"./common\";\nimport { Artifact } from \"./entities/artifact\";\nimport { Automation, AutomationRun } from \"./entities/automation\";\nimport { InboxItem } from \"./entities/inbox\";\nimport { Project } from \"./entities/project\";\nimport { Session } from \"./entities/session\";\nimport { FACTORY_EVENT_PAYLOADS } from \"./factory-api\";\nimport { GITHUB_EVENT_PAYLOADS } from \"./github\";\nimport { ConflictRecord, Notice } from \"./orchestration\";\nimport { PtyId } from \"./runner/commands\";\nimport { Settings } from \"./settings\";\nimport { Checkpoint, QueuedMessage, SetupStep } from \"./workbench\";\n\n/**\n * Untyped row of the append-only `events` table (§6): `seq, session_id, type, payload, ts`.\n * Use `EventEnvelope` to parse it into the typed union.\n */\nexport const RawEventEnvelope = z.object({\n /** Global, monotonically increasing sequence number assigned by the server. */\n seq: z.int().positive(),\n /** Session the event belongs to; null for global events (projects, settings, runner). */\n sessionId: Id.nullable(),\n type: z.string(),\n payload: z.unknown(),\n ts: Timestamp,\n});\nexport type RawEventEnvelope = z.infer<typeof RawEventEnvelope>;\n\nconst base = { seq: z.int().positive(), sessionId: Id.nullable(), ts: Timestamp };\nconst sessionBase = { seq: z.int().positive(), sessionId: Id, ts: Timestamp };\n\nfunction globalEvent<T extends string, P extends z.ZodType>(type: T, payload: P) {\n return z.object({ ...base, type: z.literal(type), payload });\n}\n\nfunction agentEvent<T extends string, P extends z.ZodType>(type: T, payload: P) {\n return z.object({ ...sessionBase, type: z.literal(`agent.${type}` as `agent.${T}`), payload });\n}\n\n/** Prefix used for persisted agent events: `agent.turn.started`, `agent.item.delta`, ... */\nexport const AGENT_EVENT_PREFIX = \"agent.\";\n\n/**\n * Typed persisted event. Agent events (§7.3) are stored as `agent.<type>` with the\n * normalized `AgentEvent` as payload; the rest are domain events written by the server\n * in the same transaction as the projections they update.\n */\nexport const EventEnvelope = z.discriminatedUnion(\"type\", [\n // Agent events, from runners.\n agentEvent(\"session.updated\", SessionUpdatedEvent),\n agentEvent(\"thread.started\", ThreadStartedEvent),\n agentEvent(\"turn.started\", TurnStartedEvent),\n agentEvent(\"turn.completed\", TurnCompletedEvent),\n agentEvent(\"turn.failed\", TurnFailedEvent),\n agentEvent(\"turn.interrupted\", TurnInterruptedEvent),\n agentEvent(\"item.started\", ItemStartedEvent),\n agentEvent(\"item.delta\", ItemDeltaEvent),\n agentEvent(\"item.updated\", ItemUpdatedEvent),\n agentEvent(\"item.completed\", ItemCompletedEvent),\n agentEvent(\"usage.updated\", UsageUpdatedEvent),\n // Domain events.\n globalEvent(\"project.created\", z.object({ project: Project })),\n globalEvent(\"project.updated\", z.object({ project: Project })),\n globalEvent(\"project.archived\", z.object({ projectId: Id })),\n /**\n * The user rearranged the project list (§13). `projectIds` is every non-archived project in\n * its new order; each one's `sortOrder` becomes its index. Archived projects keep theirs.\n */\n globalEvent(\"projects.reordered\", z.object({ projectIds: z.array(Id) })),\n globalEvent(\"session.created\", z.object({ session: Session })),\n /** Any change to a session row, including status transitions. */\n globalEvent(\"session.updated\", z.object({ session: Session })),\n globalEvent(\"inbox.created\", z.object({ item: InboxItem })),\n globalEvent(\"inbox.updated\", z.object({ item: InboxItem })),\n globalEvent(\"automation.saved\", z.object({ automation: Automation })),\n globalEvent(\"automation.deleted\", z.object({ automationId: Id })),\n globalEvent(\"automation_run.updated\", z.object({ run: AutomationRun })),\n /**\n * Scheduler state of an automation in a project changed (paused, resumed, next run skipped\n * or advanced, per-project override), or a project's automation switch (`automationId` null).\n * A hint for live views to refetch; the state itself is operational and not projected.\n */\n globalEvent(\n \"automation.updated\",\n z.object({ automationId: Id.nullable(), projectId: Id.nullable() }),\n ),\n globalEvent(\"artifact.created\", z.object({ artifact: Artifact })),\n globalEvent(\"settings.updated\", z.object({ settings: Settings })),\n globalEvent(\n \"runner.connected\",\n z.object({ runnerId: z.string(), version: z.string(), protocolVersion: z.int() }),\n ),\n globalEvent(\"runner.disconnected\", z.object({ runnerId: z.string(), reason: z.string() })),\n /** The runner started draining (upgrade or shutdown); its sessions resume afterwards. */\n globalEvent(\"runner.draining\", z.object({ runnerId: z.string(), reason: z.string() })),\n /** Progress of a worktree setup command (projected into the session's start metadata). */\n globalEvent(\"session.setup\", z.object({ sessionId: Id, step: SetupStep })),\n /** A turn checkpoint was written (projected into `checkpoints`, used for diffs). */\n globalEvent(\"checkpoint.created\", z.object({ checkpoint: Checkpoint })),\n /** A message was queued behind the running turn. */\n globalEvent(\"message.queued\", z.object({ message: QueuedMessage })),\n /** A queued message left the queue: delivered, dropped (interrupt, stop) or deleted. */\n globalEvent(\n \"message.dequeued\",\n z.object({ sessionId: Id, messageId: Id, reason: z.enum([\"sent\", \"dropped\", \"deleted\"]) }),\n ),\n /** A queued message's text was edited before delivery; its attachments stay. */\n globalEvent(\n \"message.edited\",\n z.object({ sessionId: Id, messageId: Id, text: z.string(), at: Timestamp }),\n ),\n /** A typed orchestration notice for a PM or the orchestrator (§8.2). */\n globalEvent(\"notice.created\", z.object({ notice: Notice })),\n /** Notices delivered to their target (a wake, or shown in a digest). */\n globalEvent(\"notice.delivered\", z.object({ noticeIds: z.array(Id), at: Timestamp })),\n /**\n * Delivered notices back to undelivered: the role session's turn that carried them failed, so\n * the next wake carries them again (§8.2).\n */\n globalEvent(\"notice.returned\", z.object({ noticeIds: z.array(Id), at: Timestamp })),\n /** A start request matched running work; persisted with its `conflict` inbox item (§8.4). */\n globalEvent(\"conflict.created\", z.object({ conflict: ConflictRecord })),\n /** A runner terminal exited. */\n globalEvent(\"pty.exited\", z.object({ ptyId: PtyId, exitCode: z.int().nullable() })),\n // GitHub sync (§9); `sessionId` is the PR's linked session when there is one.\n globalEvent(\"github.synced\", GITHUB_EVENT_PAYLOADS[\"github.synced\"]),\n globalEvent(\"issue.opened\", GITHUB_EVENT_PAYLOADS[\"issue.opened\"]),\n globalEvent(\"issue.labeled\", GITHUB_EVENT_PAYLOADS[\"issue.labeled\"]),\n globalEvent(\"issue.updated\", GITHUB_EVENT_PAYLOADS[\"issue.updated\"]),\n globalEvent(\"issue.commented\", GITHUB_EVENT_PAYLOADS[\"issue.commented\"]),\n globalEvent(\"pr.opened\", GITHUB_EVENT_PAYLOADS[\"pr.opened\"]),\n globalEvent(\"pr.updated\", GITHUB_EVENT_PAYLOADS[\"pr.updated\"]),\n globalEvent(\"pr.review_requested\", GITHUB_EVENT_PAYLOADS[\"pr.review_requested\"]),\n globalEvent(\"pr.checks_passed\", GITHUB_EVENT_PAYLOADS[\"pr.checks_passed\"]),\n globalEvent(\"pr.checks_failed\", GITHUB_EVENT_PAYLOADS[\"pr.checks_failed\"]),\n globalEvent(\"pr.merged\", GITHUB_EVENT_PAYLOADS[\"pr.merged\"]),\n globalEvent(\"pr.closed\", GITHUB_EVENT_PAYLOADS[\"pr.closed\"]),\n globalEvent(\"review.submitted\", GITHUB_EVENT_PAYLOADS[\"review.submitted\"]),\n // Factory loop (§10.1): the loop record, work items (with merge checks) and daily digests.\n globalEvent(\"factory.loop.updated\", FACTORY_EVENT_PAYLOADS[\"factory.loop.updated\"]),\n globalEvent(\"factory.item.updated\", FACTORY_EVENT_PAYLOADS[\"factory.item.updated\"]),\n globalEvent(\"factory.digest.created\", FACTORY_EVENT_PAYLOADS[\"factory.digest.created\"]),\n]);\nexport type EventEnvelope = z.infer<typeof EventEnvelope>;\nexport type EventType = EventEnvelope[\"type\"];\n/** Narrow an envelope by type: `EventOf<\"session.created\">`. */\nexport type EventOf<T extends EventType> = Extract<EventEnvelope, { type: T }>;\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n/** An event before the store assigns `seq` and `ts`. */\nexport type NewEvent = DistributiveOmit<EventEnvelope, \"seq\" | \"ts\">;\n\n/** Build the persisted form of an agent event for a session. */\nexport function agentEventToNewEvent(sessionId: string, event: AgentEvent): NewEvent {\n return {\n sessionId,\n type: `${AGENT_EVENT_PREFIX}${event.type}`,\n payload: event,\n } as NewEvent;\n}\n\n/** True when a persisted event carries an agent event payload. */\nexport function isAgentEnvelope(\n e: EventEnvelope,\n): e is Extract<EventEnvelope, { type: `agent.${string}` }> {\n return e.type.startsWith(AGENT_EVENT_PREFIX);\n}\n","import { z } from \"zod\";\nimport { ErrorInfo, Id, Timestamp } from \"./common\";\nimport { Automation } from \"./entities/automation\";\nimport { InboxItem } from \"./entities/inbox\";\nimport { Project } from \"./entities/project\";\nimport { ItemRecord, Session, Thread, Turn } from \"./entities/session\";\nimport { RawEventEnvelope } from \"./events\";\nimport { RoleSessionsRef } from \"./orchestration\";\nimport { ProviderInfo } from \"./provider\";\nimport { Settings } from \"./settings\";\nimport { UpdateStatus } from \"./updates\";\nimport { ScheduledRun } from \"./work\";\n\n/**\n * Server <-> UI realtime protocol (§6 \"Realtime to the UI\").\n *\n * 1. The client loads a `Snapshot` over HTTP (`GET /api/snapshot`); it includes the current `seq`.\n * 2. It opens `/ws` and sends `subscribe { fromSeq: snapshot.seq }`.\n * 3. The server sends every event with `seq > fromSeq` (catch-up), then live `events` batches.\n * 4. On reconnect the client subscribes from the last `seq` it applied.\n * 5. If the server cannot serve the gap, it sends `resync`; the client reloads the snapshot.\n */\n\n/** Runner connection state as seen by the server. */\nexport const RunnerConnectionStatus = z.object({\n state: z.enum([\"disabled\", \"starting\", \"connected\", \"disconnected\", \"incompatible\"]),\n runnerId: z.string().nullable(),\n version: z.string().nullable(),\n providers: z.array(ProviderInfo),\n lastError: z.string().nullable(),\n});\nexport type RunnerConnectionStatus = z.infer<typeof RunnerConnectionStatus>;\n\n/** Everything the app shell needs on load. Transcripts are loaded per session. */\nexport const Snapshot = z.object({\n seq: z.int().nonnegative(),\n serverVersion: z.string(),\n generatedAt: Timestamp,\n settings: Settings,\n projects: z.array(Project),\n sessions: z.array(Session),\n inbox: z.array(InboxItem),\n automations: z.array(Automation),\n /** Upcoming scheduled runs across projects (§8.4 Now / Next). */\n scheduled: z.array(ScheduledRun).default([]),\n /** The orchestrator and PM sessions (§8.1), also present in `sessions`. */\n roleSessions: RoleSessionsRef.optional(),\n runner: RunnerConnectionStatus,\n});\nexport type Snapshot = z.infer<typeof Snapshot>;\n\n/** One session's transcript (`GET /api/sessions/:id/snapshot`). */\nexport const SessionSnapshot = z.object({\n seq: z.int().nonnegative(),\n session: Session,\n threads: z.array(Thread),\n turns: z.array(Turn),\n items: z.array(ItemRecord),\n});\nexport type SessionSnapshot = z.infer<typeof SessionSnapshot>;\n\n// ---------------------------------------------------------------- client -> server\n\nexport const ClientSubscribe = z.object({\n type: z.literal(\"subscribe\"),\n /** Deliver events with `seq > fromSeq`. */\n fromSeq: z.int().nonnegative(),\n /** Restrict to these sessions (plus global events); omitted means everything. */\n sessionIds: z.array(Id).optional(),\n});\n\nexport const ClientToServerMessage = z.discriminatedUnion(\"type\", [\n ClientSubscribe,\n z.object({ type: z.literal(\"unsubscribe\") }),\n z.object({ type: z.literal(\"ping\"), id: z.string() }),\n]);\nexport type ClientToServerMessage = z.infer<typeof ClientToServerMessage>;\n\n// ---------------------------------------------------------------- server -> client\n\nexport const ServerToClientMessage = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"hello\"),\n protocolVersion: z.int().positive(),\n serverVersion: z.string(),\n /** Current head of the event log. */\n seq: z.int().nonnegative(),\n }),\n /**\n * Ordered batch of events. Payloads are sent raw; parse with `EventEnvelope` and skip\n * unknown types so older clients survive newer servers.\n */\n z.object({ type: z.literal(\"events\"), events: z.array(RawEventEnvelope) }),\n /** The client must reload its snapshot and resubscribe from `seq`. */\n z.object({\n type: z.literal(\"resync\"),\n reason: z.enum([\"gap\", \"too_far_behind\", \"server_restarted\"]),\n seq: z.int().nonnegative(),\n }),\n /** Runner connection changed (ephemeral; not in the event log). */\n z.object({ type: z.literal(\"runner\"), runner: RunnerConnectionStatus }),\n /** Update check or self-update progress changed (ephemeral; not in the event log, §16). */\n z.object({ type: z.literal(\"update\"), update: UpdateStatus }),\n z.object({ type: z.literal(\"pong\"), id: z.string() }),\n z.object({ type: z.literal(\"error\"), error: ErrorInfo }),\n]);\nexport type ServerToClientMessage = z.infer<typeof ServerToClientMessage>;\n\n/** `GET /api/health` response (unauthenticated, used by the CLI to find a running server). */\nexport const HealthResponse = z.object({\n ok: z.literal(true),\n name: z.literal(\"codeden\"),\n version: z.string(),\n uptimeSec: z.number().nonnegative(),\n});\nexport type HealthResponse = z.infer<typeof HealthResponse>;\n","import { z } from \"zod\";\nimport { Usage } from \"./agent-events\";\nimport {\n AutonomyLevel,\n ErrorInfo,\n GitHubIssueRef,\n Id,\n ProviderId,\n ReasoningEffort,\n Role,\n Timestamp,\n} from \"./common\";\nimport { InboxItemKind, InboxItemStatus } from \"./entities/inbox\";\nimport { GitHubRepo, Project } from \"./entities/project\";\nimport { ItemRecord, Session, SessionStatus, Thread, Turn } from \"./entities/session\";\nimport { UserInput } from \"./input\";\nimport { FollowupsItem } from \"./items\";\nimport { BrokenExecutable, ProviderInfo, RuntimeResponse } from \"./provider\";\nimport { ConflictDecision, StartedBy, StartWorkResult, WorkKey } from \"./work\";\nimport { SetupStep } from \"./workbench\";\nimport { ClientSubscribe, ClientToServerMessage, ServerToClientMessage } from \"./ws\";\n\n/**\n * HTTP API request/response shapes (`/api/*`) and the UI WebSocket extensions for live\n * transcripts. The server validates every request body and query with these schemas; the web\n * app types against them (and the Hono RPC `AppType`).\n */\n\n/** Error body returned by every failing API route. */\nexport const ApiError = z.object({ error: ErrorInfo });\nexport type ApiError = z.infer<typeof ApiError>;\n\n// ---------------------------------------------------------------- projects\n\n/** Package managers CodeDen recognises when adding a project (§14 step 5). */\nexport const PackageManager = z.enum([\"pnpm\", \"npm\", \"yarn\", \"bun\"]);\nexport type PackageManager = z.infer<typeof PackageManager>;\n\n/** Where a new project comes from: an existing folder, or a git URL to clone. */\nexport const ProjectSource = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"local\"), path: z.string().min(1) }),\n z.object({\n type: z.literal(\"clone\"),\n /** `https://github.com/owner/repo(.git)`, `git@github.com:owner/repo.git`, or `owner/repo`. */\n url: z.string().min(1),\n /**\n * Exact target folder. When omitted the repo is cloned into `<parentDir>/<repo>`, with\n * `parentDir` defaulting to `~/codeden-projects`.\n */\n path: z.string().min(1).optional(),\n parentDir: z.string().min(1).optional(),\n }),\n]);\nexport type ProjectSource = z.infer<typeof ProjectSource>;\n\n/** `POST /api/projects`. */\nexport const CreateProjectRequest = z.object({\n source: ProjectSource,\n /** Display name; defaults to the folder name. */\n name: z.string().trim().min(1).max(100).optional(),\n defaultProvider: ProviderId.nullable().optional(),\n autonomy: AutonomyLevel.nullable().optional(),\n});\nexport type CreateProjectRequest = z.infer<typeof CreateProjectRequest>;\n\n/** What CodeDen found in a project folder. */\nexport const ProjectDetection = z.object({\n isGitRepo: z.boolean(),\n /** Top level of the git checkout (may differ from the chosen folder). */\n gitRoot: z.string().nullable(),\n remoteUrl: z.string().nullable(),\n github: GitHubRepo.nullable(),\n defaultBranch: z.string().nullable(),\n currentBranch: z.string().nullable(),\n packageManager: PackageManager.nullable(),\n /** Suggested worktree setup commands, e.g. `pnpm install`. */\n suggestedSetupCommands: z.array(z.string()),\n});\nexport type ProjectDetection = z.infer<typeof ProjectDetection>;\n\n/** `POST /api/projects` response. */\nexport const CreateProjectResponse = z.object({\n project: Project,\n detected: ProjectDetection,\n});\nexport type CreateProjectResponse = z.infer<typeof CreateProjectResponse>;\n\n/** `PATCH /api/projects/:id`. */\nexport const UpdateProjectRequest = z.object({\n name: z.string().trim().min(1).max(100).optional(),\n defaultProvider: ProviderId.nullable().optional(),\n autonomy: AutonomyLevel.nullable().optional(),\n timezone: z.string().nullable().optional(),\n defaultBranch: z.string().nullable().optional(),\n /** Pin or unpin the project in the project list (§13). */\n pinned: z.boolean().optional(),\n});\nexport type UpdateProjectRequest = z.infer<typeof UpdateProjectRequest>;\n\n/**\n * `PUT /api/projects/order`: the new manual order of the project list (§13). Lists every\n * non-archived project exactly once; the server rejects anything else (`invalid_order`).\n */\nexport const ReorderProjectsRequest = z.object({\n projectIds: z.array(Id).max(1000),\n});\nexport type ReorderProjectsRequest = z.infer<typeof ReorderProjectsRequest>;\n\n/** `PUT /api/projects/order` response: the non-archived projects in their new order. */\nexport const ReorderProjectsResponse = z.object({ projects: z.array(Project) });\nexport type ReorderProjectsResponse = z.infer<typeof ReorderProjectsResponse>;\n\n// ---------------------------------------------------------------- sessions\n\n/**\n * Where a session runs (§9): a fresh worktree (default for agents), the repo root, or an\n * existing directory (`path`).\n */\nexport const WorkspaceRequest = z.object({\n mode: z.enum([\"worktree\", \"repo_root\", \"existing\"]).default(\"worktree\"),\n path: z.string().min(1).optional(),\n branch: z.string().min(1).optional(),\n baseRef: z.string().min(1).optional(),\n setupCommands: z.array(z.string()).optional(),\n /**\n * Fetch `origin` before creating the worktree (for a `baseRef` such as `origin/<branch>`\n * that may not be local yet). CodeDen fetches; the agent then works offline.\n */\n fetch: z.boolean().optional(),\n});\nexport type WorkspaceRequest = z.infer<typeof WorkspaceRequest>;\n\n/** `POST /api/sessions`: start agent work, with the §8.4 conflict check built in. */\nexport const StartSessionRequest = z.object({\n /** Null only for the orchestrator. */\n projectId: Id.nullable(),\n role: Role.default(\"agent\"),\n /** Provider id; omitted or `auto` picks the role default / first ready provider. */\n provider: z.union([z.literal(\"auto\"), ProviderId]).optional(),\n model: z.string().min(1).optional(),\n effort: ReasoningEffort.optional(),\n autonomy: AutonomyLevel.optional(),\n /**\n * Start in plan mode: the agent explores and proposes a plan, and implements only once the\n * plan is approved. Agent sessions on a provider with `capabilities.planMode` only.\n */\n planMode: z.boolean().optional(),\n workspace: WorkspaceRequest.prefault({}),\n /** One line describing the work; defaults to the first line of the input. */\n purpose: z.string().trim().min(1).max(300).optional(),\n /** Stable identifier of the work; derived from the issue or purpose when omitted. */\n workKey: WorkKey.optional(),\n /** Narrows the work for overlap detection (§8.4). */\n scope: z\n .object({ paths: z.array(z.string()).optional(), area: z.string().optional() })\n .optional(),\n startedBy: StartedBy.prefault({ kind: \"user\" }),\n title: z.string().trim().min(1).max(200).optional(),\n parentSessionId: Id.optional(),\n issue: GitHubIssueRef.optional(),\n /** First message; the session starts idle when omitted. */\n input: UserInput.optional(),\n /** The caller's decision when a previous attempt returned `conflict`. */\n conflict: ConflictDecision.optional(),\n});\nexport type StartSessionRequest = z.infer<typeof StartSessionRequest>;\nexport type StartSessionRequestInit = z.input<typeof StartSessionRequest>;\n\n/**\n * `POST /api/sessions` response: `StartWorkResult` (`started` / `conflict`) plus the outcomes\n * of a `ConflictDecision`: `queued` (wait), `skipped` (skip) and `joined` (join).\n */\nexport const StartSessionResponse = z.discriminatedUnion(\"status\", [\n ...StartWorkResult.options,\n z.object({\n status: z.literal(\"queued\"),\n sessionId: Id,\n /** Work this session waits for. */\n behind: z.array(Id),\n }),\n z.object({ status: z.literal(\"skipped\") }),\n z.object({ status: z.literal(\"joined\"), sessionId: Id }),\n]);\nexport type StartSessionResponse = z.infer<typeof StartSessionResponse>;\n\n/**\n * `POST /api/sessions/:id/fork`: a new agent session that continues this one's conversation\n * (the provider's native fork) in a new worktree started from its latest checkpoint.\n */\nexport const ForkSessionRequest = z.object({\n /** Defaults to the source's title followed by \"(fork)\". */\n title: z.string().trim().min(1).max(200).optional(),\n});\nexport type ForkSessionRequest = z.infer<typeof ForkSessionRequest>;\n\n/** `POST /api/sessions/:id/fork` response: the new session (it starts in the background). */\nexport const ForkSessionResponse = z.object({ sessionId: Id });\nexport type ForkSessionResponse = z.infer<typeof ForkSessionResponse>;\n\n/** Recorded with a session about how it was started (forced starts keep their reason). */\nexport const SessionStartMeta = z.object({\n workspaceMode: WorkspaceRequest.shape.mode,\n /** Set when the runner could not prepare the requested workspace and CodeDen fell back. */\n workspaceFallback: z.string().nullable(),\n forced: z.object({ reason: z.string(), conflictsWith: z.array(Id) }).nullable(),\n queuedBehind: z.array(Id),\n /** Worktree setup commands (`.codeden/project.json`) and their output, in order. */\n setup: z.array(SetupStep).optional(),\n});\nexport type SessionStartMeta = z.infer<typeof SessionStartMeta>;\n\n/** `GET /api/sessions` query. */\nexport const ListSessionsQuery = z.object({\n projectId: Id.optional(),\n status: z\n .string()\n .transform((s) => s.split(\",\"))\n .pipe(z.array(SessionStatus))\n .optional(),\n workKey: z.string().optional(),\n role: Role.optional(),\n});\nexport type ListSessionsQuery = z.infer<typeof ListSessionsQuery>;\n\n/** `GET /api/sessions/:id`. */\nexport const SessionDetail = z.object({\n session: Session,\n /** Accumulated usage across turns (token counts and cost summed; context/rate limits latest). */\n usage: Usage.nullable(),\n /** Follow-up suggestions of the latest completed root turn (§7.5). */\n followups: FollowupsItem.nullable(),\n startMeta: SessionStartMeta.nullable(),\n /** Messages waiting to be sent when the current turn ends. */\n queuedMessages: z.int().nonnegative(),\n});\nexport type SessionDetail = z.infer<typeof SessionDetail>;\n\n/** `POST /api/sessions/:id/messages`. */\nexport const SendMessageRequest = z.object({\n input: UserInput,\n /** What to do while a turn is running: queue (default), steer into it, or reject. */\n whenBusy: z.enum([\"queue\", \"steer\", \"reject\"]).default(\"queue\"),\n});\nexport type SendMessageRequest = z.infer<typeof SendMessageRequest>;\nexport type SendMessageRequestInit = z.input<typeof SendMessageRequest>;\n\nexport const SendMessageResponse = z.object({\n status: z.enum([\"sent\", \"queued\", \"steered\"]),\n});\nexport type SendMessageResponse = z.infer<typeof SendMessageResponse>;\n\n/** `POST /api/sessions/:id/steer`. */\nexport const SteerRequest = z.object({ input: UserInput });\nexport type SteerRequest = z.infer<typeof SteerRequest>;\n\n/** `POST /api/sessions/:id/respond`: answer an approval request or question. */\nexport const RespondRequest = z.object({ requestId: Id, response: RuntimeResponse });\nexport type RespondRequest = z.infer<typeof RespondRequest>;\n\n/** `GET /api/sessions/:id/threads/:threadId/items` query (positions are per thread). */\nexport const ThreadItemsQuery = z.object({\n /** Items with `position < before` (older page). */\n before: z.coerce.number().int().nonnegative().optional(),\n /** Items with `position > after` (newer page). */\n after: z.coerce.number().int().min(-1).optional(),\n limit: z.coerce.number().int().min(1).max(500).default(100),\n});\nexport type ThreadItemsQuery = z.infer<typeof ThreadItemsQuery>;\n\n/** A page of transcript items. Large tool outputs are previews (`output.truncated`). */\nexport const ThreadItemsPage = z.object({\n threadId: Id,\n items: z.array(ItemRecord),\n hasMoreBefore: z.boolean(),\n hasMoreAfter: z.boolean(),\n});\nexport type ThreadItemsPage = z.infer<typeof ThreadItemsPage>;\n\n/** `GET /api/sessions/:id/items/:itemId/output`: the full output of a tool call. */\nexport const ToolOutputResponse = z.object({\n itemId: Id,\n text: z.string(),\n totalBytes: z.int().nonnegative(),\n});\nexport type ToolOutputResponse = z.infer<typeof ToolOutputResponse>;\n\n// ---------------------------------------------------------------- inbox\n\n/** `GET /api/inbox` query. Defaults to open items. */\nexport const ListInboxQuery = z.object({\n status: InboxItemStatus.optional(),\n projectId: Id.optional(),\n sessionId: Id.optional(),\n});\nexport type ListInboxQuery = z.infer<typeof ListInboxQuery>;\n\n/**\n * `POST /api/inbox/:id/resolve`. Approvals and questions pass the `response`, which is sent\n * to the agent; other items are just marked resolved or dismissed.\n */\nexport const ResolveInboxRequest = z.object({\n response: RuntimeResponse.optional(),\n status: z.enum([\"resolved\", \"dismissed\"]).default(\"resolved\"),\n note: z.string().max(2000).optional(),\n});\nexport type ResolveInboxRequest = z.infer<typeof ResolveInboxRequest>;\n\n/** `GET /api/inbox/counts`: the sidebar badge numbers. */\nexport const InboxCounts = z.object({\n open: z.int().nonnegative(),\n byProject: z.record(z.string(), z.int().nonnegative()),\n byKind: z.partialRecord(InboxItemKind, z.int().nonnegative()),\n});\nexport type InboxCounts = z.infer<typeof InboxCounts>;\n\n// ---------------------------------------------------------------- first-run setup\n\n/**\n * A first-run check (§14): the agent CLIs (`claude`, `codex`, `opencode`), then `gh`, `git`,\n * the browser and Node.js.\n */\nexport const SetupToolId = z.enum([\"claude\", \"codex\", \"opencode\", \"gh\", \"git\", \"browser\", \"node\"]);\nexport type SetupToolId = z.infer<typeof SetupToolId>;\n\n/** Setup checks whose sign-in command the UI can run in its embedded terminal. */\nexport const LoginToolId = z.enum([\"claude\", \"codex\", \"opencode\", \"gh\"]);\nexport type LoginToolId = z.infer<typeof LoginToolId>;\n\n/** A command the UI runs in its embedded terminal to fix a check (§14 step 3). */\nexport const SetupCommand = z.object({\n kind: z.enum([\"install\", \"login\", \"upgrade\", \"configure\"]),\n /** Shown to the user and typed into the terminal. */\n command: z.string(),\n /** Docs link for manual installs. */\n url: z.string().optional(),\n});\nexport type SetupCommand = z.infer<typeof SetupCommand>;\n\n/** Result of one detection check. Never contains tokens. */\nexport const SetupCheck = z.object({\n id: SetupToolId,\n label: z.string(),\n /** `ok`: ready; `warning`: usable but needs attention; `missing`: not usable. */\n state: z.enum([\"ok\", \"warning\", \"missing\", \"error\"]),\n installed: z.boolean(),\n version: z.string().nullable(),\n executablePath: z.string().nullable(),\n /** Null when not applicable or unknown. */\n loggedIn: z.boolean().nullable(),\n authMethod: z.string().nullable(),\n account: z.string().nullable(),\n loginExpiresAt: Timestamp.nullable(),\n /** Human-readable summary of the state. */\n message: z.string(),\n /**\n * The underlying error behind the message (exit code, stderr, timeout), shown in a details\n * area. Never contains tokens.\n */\n detail: z.string().optional(),\n /**\n * Copies of the tool that were found but do not run. With `installed: false` the tool is\n * \"installed but broken\"; with a working copy they are informational.\n */\n broken: z.array(BrokenExecutable).optional(),\n fix: SetupCommand.nullable(),\n durationMs: z.int().nonnegative(),\n});\nexport type SetupCheck = z.infer<typeof SetupCheck>;\n\n/** `GET /api/setup/status`. */\nexport const SetupStatus = z.object({\n checkedAt: Timestamp,\n /** Persisted in settings once the user finishes the checklist. */\n setupCompleted: z.boolean(),\n /** At least one agent provider is installed and logged in. */\n ready: z.boolean(),\n checks: z.array(SetupCheck),\n /** Changes worth a warning (expiring login, logged-out CLI). */\n warnings: z.array(z.object({ id: SetupToolId, message: z.string() })),\n});\nexport type SetupStatus = z.infer<typeof SetupStatus>;\n\n/**\n * Claude Code support (§14): the Claude Agent SDK that drives the user's installed `claude`.\n * The published package does not ship it; it is installed from npm on first use into\n * `<home>/deps` (without its optional platform binaries). `GET /api/setup/claude-sdk`;\n * `POST /api/setup/claude-sdk/install` starts (or joins) the install.\n */\nexport const ClaudeSdkStatus = z.object({\n /** `ready`: loadable; `missing`: not installed yet; `failed`: the last install failed. */\n state: z.enum([\"ready\", \"missing\", \"installing\", \"failed\"]),\n /** The SDK version CodeDen is tested with; the only version it installs. */\n version: z.string(),\n /** `deps`: installed on demand into `location`; `workspace`: resolved from a dev checkout. */\n source: z.enum([\"deps\", \"workspace\"]),\n /** The deps folder (null for `workspace`). */\n location: z.string().nullable(),\n /** Latest progress line while installing. */\n progress: z.string().nullable(),\n /** Why the last install failed. */\n error: z.string().nullable(),\n});\nexport type ClaudeSdkStatus = z.infer<typeof ClaudeSdkStatus>;\n\n/**\n * `POST /api/providers/:id/refresh-models` response: the runner re-detected the provider and\n * asked it for its models again; `providers` is every provider's list after that refresh.\n */\nexport const RefreshModelsResponse = z.object({\n providers: z.array(ProviderInfo),\n});\nexport type RefreshModelsResponse = z.infer<typeof RefreshModelsResponse>;\n\n/** `POST /api/setup/login/:tool` response: what to run in a terminal. */\nexport const LoginCommandResponse = z.object({\n tool: LoginToolId,\n command: z.string(),\n args: z.array(z.string()),\n});\nexport type LoginCommandResponse = z.infer<typeof LoginCommandResponse>;\n\n// ---------------------------------------------------------------- folder picker and files\n\n/** `GET /api/fs/list?path=`: directories only, read-only (§13 server-side folder picker). */\nexport const FsListResponse = z.object({\n /** The listed directory (absolute), or null for the roots view. */\n path: z.string().nullable(),\n parent: z.string().nullable(),\n home: z.string(),\n /** Drives on Windows, `/` elsewhere. */\n roots: z.array(z.object({ name: z.string(), path: z.string() })),\n entries: z.array(\n z.object({\n name: z.string(),\n path: z.string(),\n hidden: z.boolean(),\n /** True when the folder looks like a git checkout. */\n isGitRepo: z.boolean(),\n }),\n ),\n truncated: z.boolean(),\n});\nexport type FsListResponse = z.infer<typeof FsListResponse>;\n\n/** Roots the config-file API may touch (§12.4): a project checkout or a provider's home. */\nexport const FileRoot = z.enum([\"project\", \"claude\", \"codex\"]);\nexport type FileRoot = z.infer<typeof FileRoot>;\n\n/** `GET /api/files` query. `path` is relative to the root. */\nexport const FileReadQuery = z.object({\n root: FileRoot,\n projectId: Id.optional(),\n path: z.string().min(1),\n});\nexport type FileReadQuery = z.infer<typeof FileReadQuery>;\n\nexport const FileContent = z.object({\n root: FileRoot,\n path: z.string(),\n absolutePath: z.string(),\n exists: z.boolean(),\n content: z.string(),\n /** Null when the file does not exist. */\n sha256: z.string().nullable(),\n sizeBytes: z.int().nonnegative(),\n});\nexport type FileContent = z.infer<typeof FileContent>;\n\n/** `PUT /api/files`. A backup is written before overwriting. */\nexport const FileWriteRequest = z.object({\n root: FileRoot,\n projectId: Id.optional(),\n path: z.string().min(1),\n content: z.string().max(2_000_000),\n /**\n * Optimistic concurrency: the sha256 the editor loaded (null = the file must not exist).\n * Omit to overwrite unconditionally.\n */\n expectedSha256: z.string().nullable().optional(),\n});\nexport type FileWriteRequest = z.infer<typeof FileWriteRequest>;\n\n// ---------------------------------------------------------------- secrets\n\n/** Secrets CodeDen may keep in the OS keychain (§6). Values are never returned. */\nexport const SecretKey = z.enum([\n \"elevenlabs.apiKey\",\n \"openai.apiKey\",\n \"gemini.apiKey\",\n \"anthropic.apiKey\",\n /** Fallback GitHub token when `gh auth token` is unavailable (§9). */\n \"github.token\",\n]);\nexport type SecretKey = z.infer<typeof SecretKey>;\n\nexport const SecretsStatus = z.object({\n backend: z.enum([\"keyring\", \"memory\"]),\n keys: z.array(z.object({ key: SecretKey, set: z.boolean() })),\n});\nexport type SecretsStatus = z.infer<typeof SecretsStatus>;\n\nexport const SetSecretRequest = z.object({ value: z.string().min(1).max(10_000) });\nexport type SetSecretRequest = z.infer<typeof SetSecretRequest>;\n\n// ---------------------------------------------------------------- UI WebSocket extensions\n\n/**\n * `subscribe` with an extra switch: `agentEvents: false` delivers only domain events\n * (projects, sessions, inbox, settings, runner), leaving transcripts to `watch_session`.\n * Live events are batched (~40ms) and consecutive text deltas of one item are merged, so seqs\n * in a batch may skip; track the highest seq seen.\n */\nexport const UiSubscribe = ClientSubscribe.extend({\n agentEvents: z.boolean().default(true),\n});\n\n/**\n * Watch one session's transcript. The server sends the latest state of every thread, turn and\n * item changed after `fromSeq` (load pages over HTTP first, then watch from their `seq`),\n * then live `transcript` updates. `threadIds` limits items/turns to those threads (child\n * threads they spawn are still announced).\n */\nexport const WatchSession = z.object({\n type: z.literal(\"watch_session\"),\n sessionId: Id,\n fromSeq: z.int().nonnegative(),\n threadIds: z.array(Id).optional(),\n});\n\nexport const UnwatchSession = z.object({ type: z.literal(\"unwatch_session\"), sessionId: Id });\n\n/** Everything the UI may send over `/ws`. */\nexport const UiClientMessage = z.discriminatedUnion(\"type\", [\n UiSubscribe,\n ...ClientToServerMessage.options.filter(\n (o): o is Exclude<(typeof ClientToServerMessage.options)[number], typeof ClientSubscribe> =>\n o !== ClientSubscribe,\n ),\n WatchSession,\n UnwatchSession,\n]);\nexport type UiClientMessage = z.infer<typeof UiClientMessage>;\n\n/** Latest state of transcript rows that changed (replace by id). Outputs are previews. */\nexport const TranscriptMessage = z.object({\n type: z.literal(\"transcript\"),\n sessionId: Id,\n /** Highest event seq reflected in this message. */\n seq: z.int().nonnegative(),\n threads: z.array(Thread),\n turns: z.array(Turn),\n items: z.array(ItemRecord),\n /** Present when the session's accumulated usage changed. */\n usage: Usage.optional(),\n});\nexport type TranscriptMessage = z.infer<typeof TranscriptMessage>;\n\n/** The server cannot replay this session's changes; reload its transcript over HTTP. */\nexport const TranscriptResyncMessage = z.object({\n type: z.literal(\"transcript_resync\"),\n sessionId: Id,\n seq: z.int().nonnegative(),\n});\n\n/** Everything the server may send over `/ws`. */\nexport const UiServerMessage = z.discriminatedUnion(\"type\", [\n ...ServerToClientMessage.options,\n TranscriptMessage,\n TranscriptResyncMessage,\n]);\nexport type UiServerMessage = z.infer<typeof UiServerMessage>;\n\n// Workbench routes (diffs, checkpoints, git, terminal, utility) live in `workbench.ts`.\nexport * from \"./workbench\";\n","import { z } from \"zod\";\nimport { StartSessionResponse } from \"./api\";\nimport { AutonomyLevel, Id, ProviderId, QuietHours, ReasoningEffort, Timestamp } from \"./common\";\nimport {\n Automation,\n AutomationAction,\n AutomationGuards,\n AutomationRun,\n AutomationRunStatus,\n AutomationTarget,\n AutomationTrigger,\n TriagePolicy,\n} from \"./entities/automation\";\nimport { InboxItem } from \"./entities/inbox\";\nimport { TriageDecision } from \"./github\";\nimport { ConflictDecision, OverlapPolicy, ScheduledRun, WorkSummary } from \"./work\";\n\n/**\n * Automations HTTP API (§10): definitions from built-in templates, `~/.codeden/automations/`,\n * a repo's `.codeden/automations/` and the database; their per-project schedule state, runs,\n * manual runs with the §8.4 conflict result, the starter set and issue triage decisions.\n */\n\n/**\n * Some guards, without defaults: only the fields given override a template's or the current\n * guards (`AutomationGuards.partial()` would fill in every default).\n */\nexport const AutomationGuardsPatch = z.object({\n overlapPolicy: OverlapPolicy.optional(),\n maxConcurrent: z.int().positive().optional(),\n maxPerDay: z.int().positive().nullable().optional(),\n quietHours: QuietHours.nullable().optional(),\n catchUpMissed: z.boolean().optional(),\n});\nexport type AutomationGuardsPatch = z.infer<typeof AutomationGuardsPatch>;\n\n/** The action kinds a Markdown automation file can declare (`action:` in the frontmatter). */\nexport const AutomationFileAction = z.enum([\"start_session\", \"message_pm\", \"triage\"]);\nexport type AutomationFileAction = z.infer<typeof AutomationFileAction>;\n\n/**\n * Frontmatter of an automation Markdown file (built-in templates, global and project files).\n * The Markdown body is the prompt (`start_session`) or the message (`message_pm`).\n */\nexport const AutomationFileFrontmatter = z.object({\n name: z.string().min(1),\n description: z.string().optional(),\n trigger: AutomationTrigger,\n action: AutomationFileAction.default(\"start_session\"),\n /** Work key of the runs; `automation:<file name>` when omitted. */\n workKey: z.string().min(1).max(200).optional(),\n title: z.string().optional(),\n provider: ProviderId.optional(),\n model: z.string().optional(),\n effort: ReasoningEffort.optional(),\n autonomy: AutonomyLevel.optional(),\n guards: AutomationGuardsPatch.optional(),\n /** Triage policy (`action: triage` only). */\n policy: TriagePolicy.optional(),\n /** Part of the starter set offered to new projects (templates only). */\n starter: z.boolean().default(false),\n /** Needs a GitHub project (issues, PRs); hidden from the starter set of local projects. */\n requiresGithub: z.boolean().default(false),\n});\nexport type AutomationFileFrontmatter = z.infer<typeof AutomationFileFrontmatter>;\n\n/** A template an automation can be created from: built in, or a global automation file. */\nexport const AutomationTemplate = z.object({\n /** File name without `.md`, e.g. `security-audit`. */\n id: z.string().min(1),\n name: z.string(),\n description: z.string().nullable(),\n source: z.enum([\"builtin\", \"global_file\"]),\n path: z.string().nullable(),\n trigger: AutomationTrigger,\n action: AutomationAction,\n guards: AutomationGuards,\n workKey: z.string(),\n starter: z.boolean(),\n requiresGithub: z.boolean(),\n});\nexport type AutomationTemplate = z.infer<typeof AutomationTemplate>;\n\n/** Schedule state of an automation in one project. */\nexport const AutomationState = z.object({\n projectId: Id,\n /** Effective: global switch, project switch, the automation and any per-project override. */\n enabled: z.boolean(),\n /** Per-project override of `enabled` for automations that target all projects. */\n enabledOverride: z.boolean().nullable(),\n /** Paused by the PM or the user (`pause_automation`): no cron or event runs. */\n paused: z.boolean(),\n /** Next cron occurrence; null for event and manual triggers or when not scheduled. */\n nextRunAt: Timestamp.nullable(),\n /** The occurrence `skip_next_run` will skip. */\n skipNextAt: Timestamp.nullable(),\n});\nexport type AutomationState = z.infer<typeof AutomationState>;\n\n/** An automation with its per-project state and latest run. */\nexport const AutomationListItem = z.object({\n automation: Automation,\n states: z.array(AutomationState),\n lastRun: AutomationRun.nullable(),\n /** Source file for file-based automations. */\n path: z.string().nullable(),\n /** File-based automations are edited in their file; only enable/disable applies here. */\n readOnly: z.boolean(),\n});\nexport type AutomationListItem = z.infer<typeof AutomationListItem>;\n\n/** A Markdown automation file that failed to parse. */\nexport const AutomationFileError = z.object({ path: z.string(), message: z.string() });\nexport type AutomationFileError = z.infer<typeof AutomationFileError>;\n\n/** `GET /api/automations?projectId=`. */\nexport const ListAutomationsQuery = z.object({ projectId: Id.optional() });\nexport type ListAutomationsQuery = z.infer<typeof ListAutomationsQuery>;\n\nexport const AutomationListResponse = z.object({\n automations: z.array(AutomationListItem),\n errors: z.array(AutomationFileError),\n});\nexport type AutomationListResponse = z.infer<typeof AutomationListResponse>;\n\n/**\n * `POST /api/automations`: from a template (`templateId`, fields override it) or from scratch\n * (`name`, `trigger`, `action`). `projectId` targets one project; omitted, all projects.\n * Created disabled unless `enabled` is true.\n */\nexport const CreateAutomationRequest = z\n .object({\n templateId: z.string().min(1).optional(),\n projectId: Id.optional(),\n name: z.string().trim().min(1).max(200).optional(),\n description: z.string().nullable().optional(),\n trigger: AutomationTrigger.optional(),\n action: AutomationAction.optional(),\n guards: AutomationGuardsPatch.optional(),\n workKey: z.string().min(1).max(200).optional(),\n enabled: z.boolean().default(false),\n })\n .refine((r) => r.templateId !== undefined || (r.name && r.trigger && r.action), {\n message: \"Pass templateId, or name, trigger and action\",\n });\nexport type CreateAutomationRequest = z.infer<typeof CreateAutomationRequest>;\n\n/** `PATCH /api/automations/:id` (database automations only). */\nexport const UpdateAutomationRequest = z.object({\n name: z.string().trim().min(1).max(200).optional(),\n description: z.string().nullable().optional(),\n trigger: AutomationTrigger.optional(),\n action: AutomationAction.optional(),\n target: AutomationTarget.optional(),\n guards: AutomationGuardsPatch.optional(),\n workKey: z.string().min(1).max(200).nullable().optional(),\n});\nexport type UpdateAutomationRequest = z.infer<typeof UpdateAutomationRequest>;\n\n/**\n * `POST /api/automations/:id/enable|disable`. With `projectId` on an all-projects automation,\n * sets that project's override; otherwise the automation's own switch.\n */\nexport const SetAutomationEnabledRequest = z.object({ projectId: Id.optional() });\nexport type SetAutomationEnabledRequest = z.infer<typeof SetAutomationEnabledRequest>;\n\n/** `POST /api/automations/:id/pause|resume|skip-next|unskip-next`. */\nexport const AutomationProjectRequest = z.object({ projectId: Id });\nexport type AutomationProjectRequest = z.infer<typeof AutomationProjectRequest>;\n\n/** `POST /api/automations/:id/skip-next`: the occurrence now skipped (null: none scheduled). */\nexport const SkipNextResponse = z.object({ skipped: ScheduledRun.nullable() });\nexport type SkipNextResponse = z.infer<typeof SkipNextResponse>;\n\n/**\n * `POST /api/automations/:id/unskip-next`: undo a skip; the next occurrence, which runs again\n * (null when nothing was skipped).\n */\nexport const UnskipNextResponse = z.object({ next: ScheduledRun.nullable() });\nexport type UnskipNextResponse = z.infer<typeof UnskipNextResponse>;\n\n/** `POST /api/automations/:id/run`: run now, with the §8.4 conflict check. */\nexport const RunAutomationRequest = z.object({\n projectId: Id,\n /** The caller's decision when a previous attempt returned `conflict`. */\n conflict: ConflictDecision.optional(),\n /** Extra `{{placeholders}}` for the prompt. */\n context: z.record(z.string(), z.string()).optional(),\n});\nexport type RunAutomationRequest = z.infer<typeof RunAutomationRequest>;\n\n/** Result of a manual, scheduled or event run. On `conflict` nothing was recorded. */\nexport const RunAutomationResponse = z.discriminatedUnion(\"status\", [\n z.object({ status: z.literal(\"started\"), run: AutomationRun, sessionId: Id.nullable() }),\n z.object({\n status: z.literal(\"queued\"),\n run: AutomationRun,\n sessionId: Id,\n behind: z.array(Id),\n }),\n z.object({ status: z.literal(\"conflict\"), existing: z.array(WorkSummary).min(1) }),\n z.object({ status: z.literal(\"skipped\"), run: AutomationRun }),\n z.object({ status: z.literal(\"joined\"), sessionId: Id }),\n]);\nexport type RunAutomationResponse = z.infer<typeof RunAutomationResponse>;\n\n/** `GET /api/automations/runs`. */\nexport const ListAutomationRunsQuery = z.object({\n projectId: Id.optional(),\n automationId: Id.optional(),\n status: AutomationRunStatus.optional(),\n limit: z.coerce.number().int().min(1).max(500).default(50),\n});\nexport type ListAutomationRunsQuery = z.infer<typeof ListAutomationRunsQuery>;\n\n/** `GET /api/automations/upcoming` (the Now / Next strip). */\nexport const UpcomingRunsQuery = z.object({\n projectId: Id.optional(),\n limit: z.coerce.number().int().min(1).max(100).default(20),\n});\nexport type UpcomingRunsQuery = z.infer<typeof UpcomingRunsQuery>;\n\n/** `POST /api/projects/:id/automations/starter`: create (and optionally enable) the starter set. */\nexport const StarterSetRequest = z.object({ enable: z.boolean().default(false) });\nexport type StarterSetRequest = z.infer<typeof StarterSetRequest>;\n\nexport const StarterSetResponse = z.object({ automations: z.array(Automation) });\nexport type StarterSetResponse = z.infer<typeof StarterSetResponse>;\n\n/** A project's automation switch (`GET|PATCH /api/projects/:id/automations/settings`). */\nexport const AutomationProjectSettings = z.object({\n projectId: Id,\n enabled: z.boolean(),\n updatedAt: Timestamp.nullable(),\n});\nexport type AutomationProjectSettings = z.infer<typeof AutomationProjectSettings>;\n\nexport const UpdateAutomationProjectSettingsRequest = z.object({ enabled: z.boolean() });\nexport type UpdateAutomationProjectSettingsRequest = z.infer<\n typeof UpdateAutomationProjectSettingsRequest\n>;\n\n/** The PM's `report_triage`: the decision it applied to a new issue. */\nexport const TriageReport = z.object({\n issueNumber: z.int().positive(),\n decision: TriageDecision,\n /** Two or three sentences: what the issue asks and why this decision. */\n summary: z.string().trim().min(1).max(2000),\n duplicateOf: z.int().positive().optional(),\n});\nexport type TriageReport = z.infer<typeof TriageReport>;\n\n/** What happened after a triage report. */\nexport const TriageReportResult = z.discriminatedUnion(\"status\", [\n /** Not `ready`: labels and comment were the whole job. */\n z.object({ status: z.literal(\"recorded\") }),\n /** `ready` and policy allowed starting without asking. */\n z.object({ status: z.literal(\"started\"), start: StartSessionResponse }),\n /** `ready`, waiting on the user's \"Should I take this on?\" decision. */\n z.object({ status: z.literal(\"inbox\"), inboxItemId: Id }),\n]);\nexport type TriageReportResult = z.infer<typeof TriageReportResult>;\n\n/** `POST /api/automations/triage/:inboxItemId/accept|decline`. */\nexport const TriageDecisionRequest = z.object({\n reason: z.string().trim().max(2000).optional(),\n provider: ProviderId.optional(),\n model: z.string().optional(),\n /** Decision when accepting returned `conflict`. */\n conflict: ConflictDecision.optional(),\n});\nexport type TriageDecisionRequest = z.infer<typeof TriageDecisionRequest>;\n\nexport const TriageDecisionResponse = z.object({\n item: InboxItem,\n /** The session start when accepted (possibly `conflict`); null when declined. */\n start: StartSessionResponse.nullable(),\n});\nexport type TriageDecisionResponse = z.infer<typeof TriageDecisionResponse>;\n","import { z } from \"zod\";\nimport { AutomationListItem } from \"./automations-api\";\nimport { Id } from \"./common\";\nimport { AutomationAction, AutomationGuards, AutomationTrigger } from \"./entities/automation\";\n\n/**\n * Sharing automations (§10): duplicate, export as the Markdown + YAML frontmatter file format\n * (one `.md`, or all of a project's as a `.zip`), and import those files back. Imports are\n * parsed with the same parser and validation as automation files, never run anything and\n * always start off.\n */\n\n/** Size limits for an import, checked by the server before anything is parsed. */\nexport const AUTOMATION_IMPORT_LIMITS = {\n /** Automation files in one import (Markdown files, zip entries or pasted text). */\n maxFiles: 50,\n /** One file's text, in UTF-16 code units (about bytes for ASCII). */\n maxFileChars: 128 * 1024,\n /** All files together, after unzipping. */\n maxTotalChars: 1024 * 1024,\n /** A zip as uploaded, before base64 (base64 makes it about a third bigger). */\n maxZipBytes: 1024 * 1024,\n /** Entries a zip may list, `.md` or not (more is refused before inflating anything). */\n maxZipEntries: 200,\n} as const;\n\n/** One Markdown automation file to import. */\nexport const AutomationImportFile = z.object({\n /** File name, e.g. `release-notes.md`; its stem becomes the default work key. */\n name: z.string().trim().min(1).max(255),\n content: z.string().max(AUTOMATION_IMPORT_LIMITS.maxFileChars),\n});\nexport type AutomationImportFile = z.infer<typeof AutomationImportFile>;\n\n/** What to import: Markdown files, a zip of them (base64) and/or pasted Markdown. */\nexport const AutomationImportSource = z\n .object({\n files: z.array(AutomationImportFile).max(AUTOMATION_IMPORT_LIMITS.maxFiles).optional(),\n /** A `.zip` of `.md` files, base64-encoded. Other entries are ignored. */\n zipBase64: z\n .string()\n .max(Math.ceil(AUTOMATION_IMPORT_LIMITS.maxZipBytes / 3) * 4 + 4)\n .optional(),\n /** One automation pasted as text. */\n text: z.string().max(AUTOMATION_IMPORT_LIMITS.maxFileChars).optional(),\n })\n .refine((s) => Boolean(s.files?.length || s.zipBase64 || s.text?.trim()), {\n message: \"Pass files, a zip or pasted text\",\n });\nexport type AutomationImportSource = z.infer<typeof AutomationImportSource>;\n\n/** The definition an import would create (no id, target or switch yet). */\nexport const AutomationDraft = z.object({\n name: z.string().min(1),\n description: z.string().nullable(),\n trigger: AutomationTrigger,\n action: AutomationAction,\n guards: AutomationGuards,\n workKey: z.string().min(1).max(200),\n});\nexport type AutomationDraft = z.infer<typeof AutomationDraft>;\n\n/** One file of an import preview: the parsed automation, or why it cannot be imported. */\nexport const AutomationImportPreviewItem = z.object({\n /** File name, unique within the import (duplicates get ` (2)`). */\n fileName: z.string(),\n /** Null when the file is invalid. */\n automation: AutomationDraft.nullable(),\n /** Validation error (bad YAML, unknown fields, invalid cron, ...); null when importable. */\n error: z.string().nullable(),\n /** Runs with Full permissions: it never asks before acting. */\n fullPermissions: z.boolean(),\n});\nexport type AutomationImportPreviewItem = z.infer<typeof AutomationImportPreviewItem>;\n\n/** `POST /api/automations/import/preview`. Parses only; nothing is saved or run. */\nexport const AutomationImportPreviewResponse = z.object({\n items: z.array(AutomationImportPreviewItem),\n});\nexport type AutomationImportPreviewResponse = z.infer<typeof AutomationImportPreviewResponse>;\n\n/**\n * `POST /api/automations/import`: re-parse the same source and create the selected files as\n * database automations, always off. `projectId` targets one project; omitted, all projects.\n */\nexport const ImportAutomationsRequest = z.object({\n source: AutomationImportSource,\n projectId: Id.optional(),\n /** File names (from the preview) to import; omitted, every valid file. */\n select: z.array(z.string()).max(AUTOMATION_IMPORT_LIMITS.maxFiles).optional(),\n});\nexport type ImportAutomationsRequest = z.infer<typeof ImportAutomationsRequest>;\n\nexport const ImportAutomationsResponse = z.object({\n /** The new automations, all off. */\n created: z.array(AutomationListItem),\n /** Selected files that could not be imported, with the reason. */\n failed: z.array(z.object({ fileName: z.string(), error: z.string() })),\n});\nexport type ImportAutomationsResponse = z.infer<typeof ImportAutomationsResponse>;\n\n/** `GET /api/automations/:id/export`: one automation in the file format. */\nexport const AutomationExport = z.object({\n /** `<slug>.md`. */\n fileName: z.string().min(1),\n markdown: z.string(),\n});\nexport type AutomationExport = z.infer<typeof AutomationExport>;\n\n/** `GET /api/automations/export?projectId=`: the query; without a project, every automation. */\nexport const ExportAutomationsQuery = z.object({ projectId: Id.optional() });\nexport type ExportAutomationsQuery = z.infer<typeof ExportAutomationsQuery>;\n\n/** All automations (of a project) as a zip of `.md` files. */\nexport const ExportAutomationsResponse = z.object({\n fileName: z.string().min(1),\n /** The zip, base64-encoded. */\n zipBase64: z.string(),\n count: z.int().nonnegative(),\n});\nexport type ExportAutomationsResponse = z.infer<typeof ExportAutomationsResponse>;\n\n/**\n * `POST /api/automations/:id/duplicate`: an editable copy (also of file-based and built-in\n * automations), off. `projectId` targets one project; omitted, the original's target.\n */\nexport const DuplicateAutomationRequest = z.object({\n projectId: Id.optional(),\n name: z.string().trim().min(1).max(200).optional(),\n});\nexport type DuplicateAutomationRequest = z.infer<typeof DuplicateAutomationRequest>;\n","import { z } from \"zod\";\nimport { Id } from \"./common\";\nimport {\n BrowserCommandResults,\n BrowserEngine,\n BrowserFrameMetadata,\n BrowserInput,\n BrowserTab,\n BrowserTabId,\n} from \"./runner/browser\";\n\n/**\n * Browser panel HTTP and WebSocket shapes (§12.2). Routes live under\n * `/api/sessions/:id/browser`; the live view is the `/ws/browser` channel. Every call acts on\n * the session's own browser context in the runner.\n */\n\n/**\n * `POST /api/sessions/:id/browser/open`: open (or reuse) the context, optionally at `url`.\n * `native`: the desktop app's window asks; a session with no browser yet opens on native views\n * when the desktop app offers them (§17), else on the runner's Chromium.\n */\nexport const BrowserOpenRequest = z.object({\n url: z.string().min(1).max(8_000).optional(),\n native: z.boolean().optional(),\n});\nexport type BrowserOpenRequest = z.infer<typeof BrowserOpenRequest>;\n\nexport const BrowserOpenResponse = z.object({\n /** CDP endpoint on 127.0.0.1 (for diagnostics; the panel never connects to it). */\n cdpUrl: z.string().nullable(),\n tabs: z.array(BrowserTab),\n /** What backs the browser; absent from older servers (`runner`). */\n engine: BrowserEngine.optional(),\n});\nexport type BrowserOpenResponse = z.infer<typeof BrowserOpenResponse>;\n\n/** `GET /api/sessions/:id/browser/tabs`. `open` is false when the session has no browser. */\nexport const BrowserTabsResponse = z.object({\n open: z.boolean(),\n tabs: z.array(BrowserTab),\n /** What backs the browser while it is open. */\n engine: BrowserEngine.optional(),\n});\nexport type BrowserTabsResponse = z.infer<typeof BrowserTabsResponse>;\n\n/** `POST /api/sessions/:id/browser/tabs`: open a new tab. Response: `{ tab }`. */\nexport const BrowserNewTabRequest = z.object({ url: z.string().min(1).max(8_000).optional() });\nexport type BrowserNewTabRequest = z.infer<typeof BrowserNewTabRequest>;\n\nexport const BrowserTabResponse = z.object({ tab: BrowserTab });\nexport type BrowserTabResponse = z.infer<typeof BrowserTabResponse>;\n\n/** `POST /api/sessions/:id/browser/navigate`. Bare `host:port` gets `http://`. */\nexport const BrowserNavigateRequest = z.object({\n url: z.string().min(1).max(8_000),\n tabId: BrowserTabId.optional(),\n});\nexport type BrowserNavigateRequest = z.infer<typeof BrowserNavigateRequest>;\n\nexport const BrowserNavigateResponse = BrowserCommandResults[\"browser.navigate\"];\nexport type BrowserNavigateResponse = z.infer<typeof BrowserNavigateResponse>;\n\n/** `POST /api/sessions/:id/browser/history`. Response: `{ url }`. */\nexport const BrowserHistoryRequest = z.object({\n action: z.enum([\"back\", \"forward\", \"reload\"]),\n tabId: BrowserTabId.optional(),\n});\nexport type BrowserHistoryRequest = z.infer<typeof BrowserHistoryRequest>;\n\n/**\n * `POST /api/sessions/:id/browser/viewport` (CSS pixels, every tab of the session). The\n * panel sizes the viewport over `/ws/browser` instead; a later panel resize replaces this.\n */\nexport const BrowserViewportRequest = z.object({\n width: z.int().min(200).max(7680),\n height: z.int().min(200).max(4320),\n deviceScaleFactor: z.number().min(0.25).max(8).optional(),\n});\nexport type BrowserViewportRequest = z.infer<typeof BrowserViewportRequest>;\n\n/** `POST /api/sessions/:id/browser/dev-server`: open `http://localhost:<port><path>` in a new tab. */\nexport const BrowserDevServerRequest = z.object({\n port: z.int().min(1).max(65535),\n path: z.string().startsWith(\"/\").max(2_000).optional(),\n});\nexport type BrowserDevServerRequest = z.infer<typeof BrowserDevServerRequest>;\n\n/** A local dev server the runner found listening (its own descendants or probed ports). */\nexport const DevServer = z.object({\n port: z.int().min(1).max(65535),\n pid: z.int().nullable(),\n url: z.string(),\n});\nexport type DevServer = z.infer<typeof DevServer>;\n\n/** `GET /api/browser/dev-servers?probe=3000,5173`. */\nexport const DevServersResponse = z.object({ servers: z.array(DevServer) });\nexport type DevServersResponse = z.infer<typeof DevServersResponse>;\n\n// ------------------------------------------------------------------ /ws/browser channel\n\n/**\n * Query of `/ws/browser`. One socket is one viewer of one session's browser. With\n * `open=1` the server opens the session's browser when it is not open yet; otherwise the\n * viewer waits and starts watching as soon as the agent (or another viewer) opens it.\n *\n * `native=1` comes from the desktop app's window, which can show native views itself (§17):\n * opens prefer native views, and the viewer starts without frames. It still gets state, tabs\n * and agent activity, and sends `watch` (and viewport reports) when the session's browser is on\n * the runner's Chromium instead.\n */\nexport const BrowserWsQuery = z.object({\n sessionId: Id,\n open: z.enum([\"0\", \"1\"]).optional(),\n native: z.enum([\"0\", \"1\"]).optional(),\n quality: z.coerce.number().int().min(10).max(100).optional(),\n maxWidth: z.coerce.number().int().min(100).max(7680).optional(),\n maxHeight: z.coerce.number().int().min(100).max(4320).optional(),\n maxFps: z.coerce.number().int().min(1).max(60).optional(),\n});\nexport type BrowserWsQuery = z.infer<typeof BrowserWsQuery>;\n\n/** Screencast settings a viewer may change with `watch`. */\nexport const BrowserScreencastSettings = z.object({\n quality: z.int().min(10).max(100).optional(),\n maxWidth: z.int().min(100).max(7680).optional(),\n maxHeight: z.int().min(100).max(4320).optional(),\n maxFps: z.int().min(1).max(60).optional(),\n});\nexport type BrowserScreencastSettings = z.infer<typeof BrowserScreencastSettings>;\n\n/**\n * A viewer's panel size: its content box in CSS pixels and its `devicePixelRatio`. Raw\n * measurements; the runner clamps them when it applies the viewport.\n */\nexport const BrowserViewportSize = z.object({\n width: z.int().min(1).max(16_384),\n height: z.int().min(1).max(16_384),\n deviceScaleFactor: z.number().min(0.25).max(8),\n});\nexport type BrowserViewportSize = z.infer<typeof BrowserViewportSize>;\n\n/** Client -> server messages on `/ws/browser` (JSON text frames). */\nexport const BrowserClientMessage = z.discriminatedUnion(\"type\", [\n /** Human input for the active tab (mouse coordinates in displayed-frame space). */\n z.object({ type: z.literal(\"input\"), input: BrowserInput }),\n /** Start (or re-tune) the screencast for this viewer. */\n z.object({ type: z.literal(\"watch\"), settings: BrowserScreencastSettings.optional() }),\n /** Stop receiving frames (tab updates still arrive); the screencast pauses with no viewers. */\n z.object({ type: z.literal(\"unwatch\") }),\n /** Open the session's browser now (same as `open=1`). */\n z.object({ type: z.literal(\"open\"), url: z.string().min(1).max(8_000).optional() }),\n /**\n * The size this viewer wants the page at: its panel's content box in CSS pixels and its\n * `devicePixelRatio`. One viewer owns the session's viewport at a time: the first to report\n * a size, until another viewer sends `claim: true` (it was focused or used). The page follows\n * the owner's reports; when the owner leaves, the most recent claimant still connected takes\n * over. The runner clamps the size (see `browser.viewport`).\n */\n BrowserViewportSize.extend({ type: z.literal(\"viewport\"), claim: z.boolean().optional() }),\n]);\nexport type BrowserClientMessage = z.infer<typeof BrowserClientMessage>;\n\n/** Server -> client messages on `/ws/browser` (JSON text frames). */\nexport const BrowserServerMessage = z.discriminatedUnion(\"type\", [\n /** Sent once after connecting, and again when the browser opens or closes. */\n z.object({\n type: z.literal(\"state\"),\n viewerId: z.string(),\n open: z.boolean(),\n watching: z.boolean(),\n tabs: z.array(BrowserTab),\n /** What backs the browser while it is open (absent from older servers: `runner`). */\n engine: BrowserEngine.optional(),\n }),\n /** A screencast frame of the active tab. */\n z.object({\n type: z.literal(\"frame\"),\n mediaType: z.enum([\"image/jpeg\", \"image/png\"]),\n /** Base64 image data. */\n data: z.string(),\n width: z.int().positive(),\n height: z.int().positive(),\n tabId: BrowserTabId.optional(),\n metadata: BrowserFrameMetadata.optional(),\n }),\n /** The session's tabs changed (opened, closed, activated, navigated, retitled). */\n z.object({\n type: z.literal(\"tabs\"),\n tabs: z.array(BrowserTab),\n engine: BrowserEngine.optional(),\n }),\n /**\n * The viewport the runner applied (CSS pixels and device scale factor). `mine` is true when\n * it follows this viewer's panel, so the panel can fill edge to edge; other viewers fit the\n * frame inside their panel instead.\n */\n z.object({\n type: z.literal(\"viewport\"),\n width: z.int().positive(),\n height: z.int().positive(),\n deviceScaleFactor: z.number().positive(),\n mine: z.boolean(),\n }),\n /**\n * Whether an agent is driving the browser: true while an agent `browser_*` tool runs and for\n * a short while after the last one. Human input is never blocked either way.\n */\n z.object({ type: z.literal(\"agent\"), acting: z.boolean() }),\n z.object({ type: z.literal(\"error\"), code: z.string(), message: z.string() }),\n]);\nexport type BrowserServerMessage = z.infer<typeof BrowserServerMessage>;\n","import { z } from \"zod\";\nimport { Id, Timestamp } from \"./common\";\nimport type { InboxItem } from \"./entities/inbox\";\nimport type { Session } from \"./entities/session\";\nimport { BrowserCookie, BrowserHandoffTab, BrowserRelayEndpoint } from \"./runner/browser\";\n\n/**\n * The desktop app (§17): an Electron shell around the same server and UI. Everything that\n * crosses between its processes (main <-> server child over Node IPC, main <-> UI through the\n * preload bridge, the OS <-> main through `codeden://` links) is defined here.\n */\n\n// ---------------------------------------------------------------- activity (tray, badge)\n\n/**\n * `GET /api/activity`: what the tray, the app icon badge and \"keep awake\" need, without\n * loading the whole snapshot. Counts never depend on which provider runs a session.\n */\nexport const ActivitySummary = z.object({\n /** Sessions with a turn starting or in progress. */\n running: z.int().nonnegative(),\n /** Sessions blocked on the user (an approval or a question). */\n waiting: z.int().nonnegative(),\n /** Open inbox items (questions, approvals, PRs to review, failures, ...). */\n inbox: z.int().nonnegative(),\n});\nexport type ActivitySummary = z.infer<typeof ActivitySummary>;\n\n/** Count running and waiting sessions and open inbox items. */\nexport function summarizeActivity(\n sessions: ReadonlyArray<Pick<Session, \"status\">>,\n inbox: ReadonlyArray<Pick<InboxItem, \"status\">>,\n): ActivitySummary {\n let running = 0;\n let waiting = 0;\n for (const s of sessions) {\n if (s.status === \"running\" || s.status === \"starting\") running++;\n else if (s.status === \"waiting\") waiting++;\n }\n return { running, waiting, inbox: inbox.filter((i) => i.status === \"open\").length };\n}\n\n// ---------------------------------------------------------------- desktop updates\n\n/**\n * Where the desktop updater is. `available`: a newer release was found and is not downloaded\n * yet; `downloaded`: it installs on restart (or on quit in `auto` mode); `installing`: the app\n * is stopping the runner and handing over to the installer.\n */\nexport const DesktopUpdatePhase = z.enum([\n \"idle\",\n \"checking\",\n \"available\",\n \"downloading\",\n \"downloaded\",\n \"installing\",\n \"error\",\n]);\nexport type DesktopUpdatePhase = z.infer<typeof DesktopUpdatePhase>;\n\n/** The desktop updater's state, mirrored into `GET /api/updates` for the update banner. */\nexport const DesktopUpdateState = z.object({\n phase: DesktopUpdatePhase,\n /** The running app version. */\n current: z.string(),\n /** The newest release found, null until a check succeeded. */\n latest: z.string().nullable(),\n checkedAt: Timestamp.nullable(),\n /** Download progress (0-100) while `downloading`. */\n percent: z.number().min(0).max(100).nullable(),\n /** Why the last check or download failed. */\n error: z.string().nullable(),\n /** Set when this build cannot update itself (a development run, an unsigned macOS app). */\n unsupported: z.string().nullable(),\n});\nexport type DesktopUpdateState = z.infer<typeof DesktopUpdateState>;\n\n/** What the server asks the desktop updater to do (driven by the update banner and policy). */\nexport const DesktopUpdateCommand = z.enum([\"check\", \"download\", \"install\"]);\nexport type DesktopUpdateCommand = z.infer<typeof DesktopUpdateCommand>;\n\n// ---------------------------------------------------------------- main <-> server child IPC\n\n/** Server child -> desktop main process. */\nexport const DesktopServerMessage = z.discriminatedUnion(\"type\", [\n /** Listening; `launchUrl` authenticates the window on first load. */\n z.object({\n type: z.literal(\"ready\"),\n url: z.string(),\n port: z.int().min(1).max(65535),\n launchUrl: z.string(),\n version: z.string(),\n }),\n /** The server could not start (`code` is e.g. `EADDRINUSE`). */\n z.object({ type: z.literal(\"failed\"), message: z.string(), code: z.string().nullable() }),\n /** Run an updater command; answered with `update.done` carrying the same `id`. */\n z.object({ type: z.literal(\"update.command\"), id: z.string(), command: DesktopUpdateCommand }),\n]);\nexport type DesktopServerMessage = z.infer<typeof DesktopServerMessage>;\n\n/** Desktop main process -> server child. */\nexport const DesktopHostMessage = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"update.state\"), state: DesktopUpdateState }),\n z.object({ type: z.literal(\"update.done\"), id: z.string(), error: z.string().nullable() }),\n /** Close the server; with `stopRunner` the runner drains and exits too (as `codeden stop`). */\n z.object({ type: z.literal(\"shutdown\"), stopRunner: z.boolean() }),\n]);\nexport type DesktopHostMessage = z.infer<typeof DesktopHostMessage>;\n\n// ---------------------------------------------------------------- codeden:// links\n\n/** The custom URL scheme the desktop app registers. */\nexport const DEEP_LINK_SCHEME = \"codeden\";\n\n/** Where a `codeden://` link points. */\nexport const DeepLinkTarget = z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"home\") }),\n z.object({ kind: z.literal(\"inbox\") }),\n z.object({ kind: z.literal(\"session\"), sessionId: Id }),\n z.object({ kind: z.literal(\"project\"), projectId: Id }),\n z.object({ kind: z.literal(\"settings\"), section: z.string().nullable() }),\n]);\nexport type DeepLinkTarget = z.infer<typeof DeepLinkTarget>;\n\nconst SEGMENT = /^[A-Za-z0-9_-]{1,200}$/;\n\n/**\n * Parse `codeden://session/<id>`, `codeden://project/<id>`, `codeden://inbox`,\n * `codeden://settings[/<section>]` or `codeden://` (home). Anything else, including other\n * schemes and ids with unexpected characters, is null.\n */\nexport function parseDeepLink(raw: string): DeepLinkTarget | null {\n let url: URL;\n try {\n url = new URL(raw.trim());\n } catch {\n return null;\n }\n if (url.protocol !== `${DEEP_LINK_SCHEME}:`) return null;\n // `codeden://session/abc` parses with host \"session\"; `codeden:session/abc` without.\n const parts = [url.host, ...url.pathname.split(\"/\")].filter(Boolean).map(decodeSegment);\n if (parts.some((p) => p === null || !SEGMENT.test(p))) return null;\n const [kind, id, ...rest] = parts as string[];\n if (rest.length > 0) return null;\n switch (kind) {\n case undefined:\n case \"home\":\n return id === undefined ? { kind: \"home\" } : null;\n case \"inbox\":\n return id === undefined ? { kind: \"inbox\" } : null;\n case \"session\":\n return id ? { kind: \"session\", sessionId: id } : null;\n case \"project\":\n return id ? { kind: \"project\", projectId: id } : null;\n case \"settings\":\n return { kind: \"settings\", section: id ?? null };\n default:\n return null;\n }\n}\n\nfunction decodeSegment(segment: string): string | null {\n try {\n return decodeURIComponent(segment);\n } catch {\n return null;\n }\n}\n\n/** The UI route a link opens, e.g. `/sessions/<id>`. */\nexport function deepLinkPath(target: DeepLinkTarget): string {\n switch (target.kind) {\n case \"home\":\n return \"/\";\n case \"inbox\":\n return \"/inbox\";\n case \"session\":\n return `/sessions/${encodeURIComponent(target.sessionId)}`;\n case \"project\":\n return `/projects/${encodeURIComponent(target.projectId)}`;\n case \"settings\":\n return target.section ? `/settings/${encodeURIComponent(target.section)}` : \"/settings\";\n }\n}\n\n/** The `codeden://` link for a target (the inverse of `parseDeepLink`). */\nexport function deepLinkUrl(target: DeepLinkTarget): string {\n const base = `${DEEP_LINK_SCHEME}://`;\n switch (target.kind) {\n case \"home\":\n return base;\n case \"inbox\":\n return `${base}inbox`;\n case \"session\":\n return `${base}session/${encodeURIComponent(target.sessionId)}`;\n case \"project\":\n return `${base}project/${encodeURIComponent(target.projectId)}`;\n case \"settings\":\n return target.section\n ? `${base}settings/${encodeURIComponent(target.section)}`\n : `${base}settings`;\n }\n}\n\n// ---------------------------------------------------------------- the preload bridge\n\n/** Facts about the desktop app, for About and feature detection. */\nexport const DesktopInfo = z.object({\n version: z.string(),\n platform: z.enum([\"win32\", \"darwin\", \"linux\"]),\n /** True for an installed build (false when run from the repository). */\n packaged: z.boolean(),\n /** The app started this server (false when it attached to one started by `codeden`). */\n ownsServer: z.boolean(),\n /** The OS lets the app start at login (not on Linux AppImage, for example). */\n launchAtLoginSupported: z.boolean(),\n /**\n * The app can show session browsers as native views (§17 Phase 2), through\n * `CodedenDesktopApi.browser`. Absent from older apps.\n */\n nativeBrowser: z.boolean().optional(),\n});\nexport type DesktopInfo = z.infer<typeof DesktopInfo>;\n\n/** A native notification request from the UI. */\nexport const DesktopNotification = z.object({\n title: z.string().min(1).max(200),\n body: z.string().max(2000).optional(),\n /** Passed back to `onNotificationClick` when the user clicks it. */\n tag: z.string().max(200).optional(),\n});\nexport type DesktopNotification = z.infer<typeof DesktopNotification>;\n\n/**\n * `window.codedenDesktop`, exposed by the desktop app's preload script through\n * `contextBridge`. The UI never asks \"am I in Electron?\": it checks that this object exists\n * and builds the desktop `PlatformBridge` (§13) from it. Every method validates its input in\n * the main process.\n */\nexport interface CodedenDesktopApi {\n info(): Promise<DesktopInfo>;\n /** Native folder picker; resolves with an absolute path, or null when cancelled. */\n pickFolder(opts?: { title?: string; defaultPath?: string }): Promise<string | null>;\n notify(notification: DesktopNotification): void;\n /** Called with the `tag` of a notification the user clicked (the window is focused first). */\n onNotificationClick(listener: (tag: string) => void): () => void;\n /** Open an http(s) or mailto link in the system browser. */\n openExternal(url: string): void;\n /** Unread count on the app icon (dock badge, taskbar overlay, Unity launcher). */\n setBadge(count: number): void;\n /** Called with a UI route (e.g. `/sessions/<id>`) when a `codeden://` link is opened. */\n onNavigate(listener: (path: string) => void): () => void;\n /** Native browser views (§17 Phase 2); absent from older apps. */\n browser?: CodedenDesktopBrowserApi;\n}\n\n// ---------------------------------------------------------------- native browser views\n\n/**\n * Where a session's native view goes: the panel's content box in the UI page's CSS pixels\n * (`getBoundingClientRect`). The main process scales it by the window's zoom and snaps it to\n * device pixels.\n */\nexport const NativeBrowserBounds = z.object({\n x: z.number().min(-16_384).max(16_384),\n y: z.number().min(-16_384).max(16_384),\n width: z.number().min(0).max(16_384),\n height: z.number().min(0).max(16_384),\n});\nexport type NativeBrowserBounds = z.infer<typeof NativeBrowserBounds>;\n\n/** `browser.show` over the bridge, validated in the main process. */\nexport const NativeBrowserShow = z.object({ sessionId: Id, bounds: NativeBrowserBounds });\nexport type NativeBrowserShow = z.infer<typeof NativeBrowserShow>;\n\n/**\n * A CodeDen shortcut pressed while a native view had keyboard focus (the view would otherwise\n * swallow it). The UI replays it as a `keydown` on its window.\n */\nexport const NativeBrowserShortcut = z.object({\n key: z.string().min(1).max(40),\n code: z.string().max(40),\n ctrlKey: z.boolean(),\n metaKey: z.boolean(),\n altKey: z.boolean(),\n shiftKey: z.boolean(),\n});\nexport type NativeBrowserShortcut = z.infer<typeof NativeBrowserShortcut>;\n\n/**\n * App shortcuts a focused native view hands to the UI instead of the page, as combos in the\n * UI's shortcut registry format (`mod` is Ctrl, or Cmd on macOS). Only combos with Ctrl/Cmd or\n * Alt: typing in the page is never taken away.\n */\nexport const NATIVE_BROWSER_APP_SHORTCUTS = [\n \"mod+k\",\n \"mod+shift+l\",\n \"mod+,\",\n \"alt+o\",\n \"alt+i\",\n \"mod+b\",\n \"mod+\\\\\",\n \"mod+j\",\n \"alt+1\",\n \"alt+2\",\n \"alt+3\",\n \"alt+4\",\n \"alt+5\",\n \"alt+6\",\n \"mod+.\",\n \"mod+shift+m\",\n \"alt+m\",\n] as const;\n\n/**\n * `window.codedenDesktop.browser`: shows a session's native browser view (one per tab, the\n * active tab on top) over the panel. Tabs, navigation and agent tools go through the server and\n * the runner, as for the screencast; this API only places the view, which the UI can't do.\n */\nexport interface CodedenDesktopBrowserApi {\n /** Show the session's active view over `bounds` (and hide every other session's views). */\n show(sessionId: string, bounds: NativeBrowserBounds): void;\n /** Hide the session's views: the panel is hidden, or a menu or dialog covers it. */\n hide(sessionId: string): void;\n /** A PNG data URL of the session's active view, for a placeholder while it is hidden. */\n capture(sessionId: string): Promise<string | null>;\n /** Open DevTools for the session's active view. */\n inspect(sessionId: string): void;\n /** App shortcuts pressed while a native view had keyboard focus. */\n onShortcut(listener: (shortcut: NativeBrowserShortcut) => void): () => void;\n}\n\n// ---------------------------------------------------------------- the browser host channel\n\n/**\n * `/ws/browser-host`: the desktop app's main process offers native browser views to the server\n * (§17 Phase 2). Loopback only, with the install token, in both directions of the app's two\n * modes (it started the server, or attached to one `codeden` started). One app per home.\n */\n\n/** Desktop app -> server. */\nexport const BrowserHostClientMessage = z.discriminatedUnion(\"type\", [\n /** Sent once on connect: this app can host native views. */\n z.object({ type: z.literal(\"hello\"), version: z.string().max(100) }),\n /** Answer to `attach`: the session's relay. */\n z.object({ type: z.literal(\"attached\"), id: z.string().max(100), relay: BrowserRelayEndpoint }),\n /** Answer to `attach` when the app can't host the session (the server falls back). */\n z.object({ type: z.literal(\"failed\"), id: z.string().max(100), message: z.string().max(2_000) }),\n /**\n * The app is quitting: move these sessions to the runner's Chromium (tabs at their URLs, with\n * their cookies). Answered with `handoff.done` once the runner has them, or not at all if the\n * server is gone (the app quits after a timeout).\n */\n z.object({\n type: z.literal(\"handoff\"),\n id: z.string().max(100),\n sessions: z\n .array(\n z.object({\n sessionId: Id,\n tabs: z.array(BrowserHandoffTab).max(50),\n cookies: z.array(BrowserCookie).max(5_000),\n }),\n )\n .max(500),\n }),\n]);\nexport type BrowserHostClientMessage = z.infer<typeof BrowserHostClientMessage>;\n\n/** Server -> desktop app. */\nexport const BrowserHostServerMessage = z.discriminatedUnion(\"type\", [\n /** Create (or reuse) the session's native browser and answer with its relay. */\n z.object({ type: z.literal(\"attach\"), id: z.string().max(100), sessionId: Id }),\n /** The hand-off finished; `failed` lists sessions the runner could not take over. */\n z.object({\n type: z.literal(\"handoff.done\"),\n id: z.string().max(100),\n failed: z.array(Id),\n }),\n]);\nexport type BrowserHostServerMessage = z.infer<typeof BrowserHostServerMessage>;\n","import { z } from \"zod\";\nimport { Id } from \"./common\";\nimport { Artifact } from \"./entities/artifact\";\n\n/**\n * Image generation settings screen and test button (§12.5). The `generate_image` MCP tool\n * itself is described in the server's tool registry.\n */\n\nexport const ImageEngineId = z.enum([\"codex\", \"gemini\", \"openai\"]);\nexport type ImageEngineId = z.infer<typeof ImageEngineId>;\n\n/** One engine as the Settings screen shows it. */\nexport const ImageEngineStatus = z.object({\n id: ImageEngineId,\n label: z.string(),\n available: z.boolean(),\n /** Why it is unavailable, or a note when available (e.g. the login method). */\n reason: z.string().optional(),\n requiresApiKey: z.boolean(),\n referenceImages: z.boolean(),\n exactSize: z.boolean(),\n defaultModel: z.string(),\n});\nexport type ImageEngineStatus = z.infer<typeof ImageEngineStatus>;\n\n/** Images generated today (local date), for the daily caps. */\nexport const ImageUsage = z.object({\n /** `YYYY-MM-DD`. */\n date: z.string(),\n total: z.int().nonnegative(),\n byProject: z.record(z.string(), z.int().nonnegative()),\n});\nexport type ImageUsage = z.infer<typeof ImageUsage>;\n\n/** `GET /api/images/engines?projectId=`: engines, the one `generate_image` would use, usage. */\nexport const ImageEnginesResponse = z.object({\n engines: z.array(ImageEngineStatus),\n /** The engine chosen for these settings (with the project's override applied), or why none. */\n active: z.object({ engine: ImageEngineId.nullable(), reason: z.string().optional() }),\n usage: ImageUsage,\n /** Effective daily cap for the project (or the global cap without one). */\n dailyCap: z.int().nonnegative(),\n});\nexport type ImageEnginesResponse = z.infer<typeof ImageEnginesResponse>;\n\n/**\n * `POST /api/images/test`: check an engine (default: the active one). With `generate`\n * (default true) one small image is generated and stored as an artifact; it counts toward\n * the daily cap.\n */\nexport const ImageTestRequest = z.object({\n engine: z.enum([\"auto\", \"codex\", \"gemini\", \"openai\"]).optional(),\n projectId: Id.optional(),\n generate: z.boolean().optional(),\n prompt: z.string().min(1).max(2_000).optional(),\n});\nexport type ImageTestRequest = z.infer<typeof ImageTestRequest>;\n\nexport const ImageTestResponse = z.object({\n ok: z.boolean(),\n engine: ImageEngineId.nullable(),\n model: z.string().optional(),\n durationMs: z.int().nonnegative(),\n /** The generated test image. */\n artifact: Artifact.optional(),\n error: z.object({ code: z.string(), message: z.string() }).optional(),\n});\nexport type ImageTestResponse = z.infer<typeof ImageTestResponse>;\n","import { z } from \"zod\";\nimport { Timestamp } from \"./common\";\n\n/**\n * Network access (§15.1): an opt-in way to open CodeDen from a phone or tablet on the same\n * network, or over the user's own VPN. Off by default; turning it on needs a password. The\n * runner, `/mcp` and network management stay loopback-only whatever this says.\n */\n\n/** Shortest accepted network-access password. */\nexport const PASSWORD_MIN_LENGTH = 15;\n/** Longest accepted password (keeps hashing cheap and bounded). */\nexport const PASSWORD_MAX_LENGTH = 256;\n/** How long a remote device stays signed in. */\nexport const REMOTE_SESSION_DAYS = 90;\n\n/** The password rules in plain words, shown next to the password field. */\nexport const PASSWORD_RULE_TEXT =\n \"Use at least 15 characters. A short sentence or a few random words works well. Very common passwords, repeated characters and simple sequences such as abcdef… or 12345… are refused.\";\n\n/** Base words of very common passwords; a password made of one of these plus digits is refused. */\nconst COMMON_WORDS = new Set([\n \"password\",\n \"passw0rd\",\n \"letmein\",\n \"welcome\",\n \"admin\",\n \"administrator\",\n \"iloveyou\",\n \"qwerty\",\n \"monkey\",\n \"dragon\",\n \"football\",\n \"baseball\",\n \"sunshine\",\n \"princess\",\n \"superman\",\n \"batman\",\n \"trustno\",\n \"master\",\n \"shadow\",\n \"michael\",\n \"jennifer\",\n \"computer\",\n \"secret\",\n \"changeme\",\n \"codeden\",\n \"default\",\n \"login\",\n \"hello\",\n \"abc\",\n \"test\",\n \"guest\",\n \"root\",\n \"starwars\",\n \"whatever\",\n \"freedom\",\n \"mustang\",\n \"pokemon\",\n \"charlie\",\n \"correcthorsebatterystaple\",\n]);\n\n/** Character runs a \"sequence\" password walks along (alphabet, digits, keyboard rows). */\nconst SEQUENCES = [\n \"abcdefghijklmnopqrstuvwxyz\",\n \"0123456789\",\n \"qwertyuiopasdfghjklzxcvbnm\",\n \"qwertzuiopasdfghjklyxcvbnm\",\n \"azertyuiopqsdfghjklmwxcvbn\",\n \"1qaz2wsx3edc4rfv5tgb6yhn7ujm8ik9ol0p\",\n \"qazwsxedcrfvtgbyhnujmikolp\",\n \"1234567890qwertyuiopasdfghjklzxcvbnm\",\n];\n\n/** True when `text` is one short unit repeated (`abcabcabc`, `passwordpassword`). */\nfunction isRepeatedUnit(text: string): boolean {\n for (let size = 1; size <= text.length / 2; size++) {\n if (text.length % size !== 0) continue;\n if (text.slice(0, size).repeat(text.length / size) === text) return true;\n }\n return false;\n}\n\n/** True when `text` walks along one of the known sequences, forwards or backwards (wrapping). */\nfunction isSequence(text: string): boolean {\n return SEQUENCES.some((seq) => {\n const looped = seq.repeat(Math.ceil(text.length / seq.length) + 2);\n const reversed = [...looped].reverse().join(\"\");\n return looped.includes(text) || reversed.includes(text);\n });\n}\n\n/**\n * Why `password` can't be used for network access, in plain words, or null when it is fine.\n * Shared by the server (which enforces it) and the UI (which explains it as you type).\n */\nexport function passwordProblem(password: string): string | null {\n if (password.length < PASSWORD_MIN_LENGTH) {\n return `Use at least ${PASSWORD_MIN_LENGTH} characters (this one has ${password.length}).`;\n }\n if (password.length > PASSWORD_MAX_LENGTH) {\n return `Use at most ${PASSWORD_MAX_LENGTH} characters.`;\n }\n const lower = password.toLowerCase();\n const compact = lower.replace(/\\s+/g, \"\");\n if (new Set(compact).size < 5 || isRepeatedUnit(compact)) {\n return \"That repeats the same few characters. Try a few random words instead.\";\n }\n if (isSequence(compact)) {\n return \"That is a simple sequence. Try a few random words instead.\";\n }\n const letters = lower.replace(/[^a-z]/g, \"\");\n const words = lower.split(/[^a-z]+/).filter(Boolean);\n const onlyCommon =\n letters.length > 0 &&\n (COMMON_WORDS.has(letters) ||\n isRepeatedUnitOf(letters, COMMON_WORDS) ||\n (words.length > 0 && words.every((w) => COMMON_WORDS.has(w))));\n if (onlyCommon) {\n return \"That is too close to a very common password. Try a few random words instead.\";\n }\n return null;\n}\n\nfunction isRepeatedUnitOf(text: string, units: ReadonlySet<string>): boolean {\n for (const unit of units) {\n if (text.length % unit.length === 0 && unit.repeat(text.length / unit.length) === text) {\n return true;\n }\n }\n return false;\n}\n\n/** Which kind of address the server answers on. `vpn` covers Tailscale's `100.64.0.0/10`. */\nexport const NetworkAddressKind = z.enum([\"local\", \"lan\", \"vpn\"]);\nexport type NetworkAddressKind = z.infer<typeof NetworkAddressKind>;\n\n/** One address CodeDen can be opened on, with the URL a phone would scan. */\nexport const NetworkAddress = z.object({\n kind: NetworkAddressKind,\n /** Human label, e.g. \"This computer\", \"Wi-Fi (192.168.1.20)\", \"Tailscale\". */\n label: z.string(),\n /** The interface the address belongs to (`Wi-Fi`, `eth0`, `tailscale0`), or null for localhost. */\n interfaceName: z.string().nullable(),\n /** The bare host: `localhost` or an IPv4 address. */\n host: z.string(),\n /** `http://<host>:<port>`. */\n url: z.string(),\n});\nexport type NetworkAddress = z.infer<typeof NetworkAddress>;\n\n/** A signed-in remote device, as listed in Settings › Network access (never the token). */\nexport const RemoteDevice = z.object({\n id: z.string(),\n /** The browser's user agent when it signed in (trimmed). */\n label: z.string(),\n /** The address it signed in from. */\n address: z.string().nullable(),\n createdAt: Timestamp,\n lastSeenAt: Timestamp,\n expiresAt: Timestamp,\n /** The device making this request. */\n current: z.boolean(),\n});\nexport type RemoteDevice = z.infer<typeof RemoteDevice>;\n\n/**\n * `GET /api/network`: whether network access is on, where CodeDen answers, and who is signed\n * in. `remote` tells the caller whether it is itself a remote device (management is\n * loopback-only, so the UI shows the controls read-only there).\n */\nexport const NetworkStatus = z.object({\n enabled: z.boolean(),\n passwordSet: z.boolean(),\n passwordSetAt: Timestamp.nullable(),\n /** Where the HTTP listener is bound right now. */\n listening: z.enum([\"loopback\", \"network\"]),\n port: z.int().nonnegative(),\n /** Addresses CodeDen answers on: localhost always, LAN and VPN addresses when enabled. */\n addresses: z.array(NetworkAddress),\n /** Addresses it would answer on once enabled (for the off state's preview). */\n candidates: z.array(NetworkAddress),\n devices: z.array(RemoteDevice),\n remote: z.boolean(),\n});\nexport type NetworkStatus = z.infer<typeof NetworkStatus>;\n\n/**\n * `POST /api/network/password` (loopback only): set a password, or let the server generate a\n * passphrase. Either way every remote device is signed out.\n */\nexport const SetNetworkPasswordRequest = z.union([\n z.object({ password: z.string().min(1).max(PASSWORD_MAX_LENGTH) }),\n z.object({ generate: z.literal(true) }),\n]);\nexport type SetNetworkPasswordRequest = z.infer<typeof SetNetworkPasswordRequest>;\n\n/** Response to setting the password: the generated passphrase is returned once, never again. */\nexport const SetNetworkPasswordResponse = z.object({\n status: NetworkStatus,\n generated: z.string().nullable(),\n});\nexport type SetNetworkPasswordResponse = z.infer<typeof SetNetworkPasswordResponse>;\n\n/** `PUT /api/network` (loopback only): turn network access on or off. */\nexport const SetNetworkAccessRequest = z.object({ enabled: z.boolean() });\nexport type SetNetworkAccessRequest = z.infer<typeof SetNetworkAccessRequest>;\n\n/** `POST /api/auth/sign-in` from a remote device. */\nexport const SignInRequest = z.object({ password: z.string().max(PASSWORD_MAX_LENGTH) });\nexport type SignInRequest = z.infer<typeof SignInRequest>;\n\n/** `GET /api/auth/status`: what the sign-in page needs to know (public). */\nexport const AuthStatus = z.object({\n /** The caller is not on this machine. */\n remote: z.boolean(),\n /** The caller has a valid session (remote) or install-token cookie (local). */\n signedIn: z.boolean(),\n networkEnabled: z.boolean(),\n});\nexport type AuthStatus = z.infer<typeof AuthStatus>;\n\n/** A failed sign-in: `retryAfterSec` is set while the address must wait or is locked out. */\nexport const SignInError = z.object({\n error: z.object({\n code: z.enum([\"invalid_password\", \"rate_limited\", \"locked_out\", \"network_off\"]),\n message: z.string(),\n retryAfterSec: z.int().nonnegative().nullable(),\n }),\n});\nexport type SignInError = z.infer<typeof SignInError>;\n\n/** A stored remote session: only the SHA-256 hash of its token is kept. */\nexport const RemoteSessionRecord = z.object({\n id: z.string(),\n tokenHash: z.string().regex(/^[0-9a-f]{64}$/),\n label: z.string(),\n address: z.string().nullable(),\n createdAt: Timestamp,\n lastSeenAt: Timestamp,\n expiresAt: Timestamp,\n});\nexport type RemoteSessionRecord = z.infer<typeof RemoteSessionRecord>;\n\n/**\n * `<home>/remote-access.json` (mode 0600): the network switch, the password hash (scrypt,\n * salted; never the password) and the remote sessions. Kept out of `settings.json` so the\n * settings API can't switch network access on without the checks.\n */\nexport const RemoteAccessFile = z.object({\n schemaVersion: z.literal(1).default(1),\n enabled: z.boolean().default(false),\n password: z\n .object({\n /** `scrypt$<N>$<r>$<p>$<salt b64>$<hash b64>`. */\n hash: z.string().startsWith(\"scrypt$\"),\n setAt: Timestamp,\n })\n .nullable()\n .default(null),\n sessions: z.array(RemoteSessionRecord).default([]),\n});\nexport type RemoteAccessFile = z.infer<typeof RemoteAccessFile>;\n","import { z } from \"zod\";\nimport { StartSessionResponse } from \"./api\";\nimport { AutonomyLevel, Id, ReasoningEffort } from \"./common\";\nimport { InboxItemStatus } from \"./entities/inbox\";\nimport { Session } from \"./entities/session\";\nimport { UserInput } from \"./input\";\nimport { ConflictRecord, NoticeTarget } from \"./orchestration\";\nimport { ConflictDecision } from \"./work\";\n\n/** HTTP shapes for the orchestrator and PM chats, notices and conflicts (`/api/orchestration`). */\n\n/** `GET|POST /api/orchestration/orchestrator` and `.../projects/:id/pm`. */\nexport const RoleSessionResponse = z.object({ session: Session.nullable() });\nexport type RoleSessionResponse = z.infer<typeof RoleSessionResponse>;\n\n/** `POST .../orchestrator/messages` and `.../projects/:id/pm/messages`. */\nexport const RoleMessageRequest = z.object({\n input: UserInput,\n whenBusy: z.enum([\"queue\", \"steer\", \"reject\"]).default(\"queue\"),\n});\nexport type RoleMessageRequest = z.infer<typeof RoleMessageRequest>;\nexport type RoleMessageRequestInit = z.input<typeof RoleMessageRequest>;\n\nexport const RoleMessageResponse = z.object({\n sessionId: Id,\n status: z.enum([\"sent\", \"queued\", \"steered\"]),\n});\nexport type RoleMessageResponse = z.infer<typeof RoleMessageResponse>;\n\n/** `GET /api/orchestration/notices` query. */\nexport const ListNoticesQuery = z.object({\n projectId: Id.optional(),\n target: NoticeTarget.optional(),\n limit: z.coerce.number().int().min(1).max(500).default(100),\n});\nexport type ListNoticesQuery = z.infer<typeof ListNoticesQuery>;\n\n/** `GET /api/conflicts` query. Defaults to open conflicts. */\nexport const ListConflictsQuery = z.object({\n status: InboxItemStatus.optional(),\n projectId: Id.optional(),\n});\nexport type ListConflictsQuery = z.infer<typeof ListConflictsQuery>;\n\n/** `POST /api/conflicts/:id/resolve`: the decision (wait, skip, join or force with a reason). */\nexport const ResolveConflictRequest = ConflictDecision;\nexport type ResolveConflictRequest = z.infer<typeof ResolveConflictRequest>;\n\nexport const ResolveConflictResponse = z.object({\n conflict: ConflictRecord,\n result: StartSessionResponse,\n});\nexport type ResolveConflictResponse = z.infer<typeof ResolveConflictResponse>;\n\n/**\n * `PATCH /api/sessions/:id`: change the model, effort, autonomy, plan mode or title\n * mid-session. Model and effort apply on the next turn (a running turn keeps its settings);\n * `null` returns to the role default.\n */\nexport const UpdateSessionRequest = z\n .object({\n model: z.string().min(1).nullable().optional(),\n effort: ReasoningEffort.nullable().optional(),\n /**\n * Autonomy level (§11.2), saved on the session and pushed to the live provider session.\n * It applies from the next tool call when the provider reports `liveAutonomy`, otherwise\n * from the next turn. Approvals already waiting stay waiting.\n */\n autonomy: AutonomyLevel.optional(),\n /**\n * Turn plan mode on or off (agent sessions on a provider with `capabilities.planMode`).\n * Saved on the session and pushed to the live provider session like `autonomy`. Off\n * returns the agent to the session's permission level.\n */\n planMode: z.boolean().optional(),\n title: z.string().trim().min(1).max(200).optional(),\n })\n .refine(\n (r) =>\n r.model !== undefined ||\n r.effort !== undefined ||\n r.autonomy !== undefined ||\n r.planMode !== undefined ||\n r.title !== undefined,\n { message: \"Nothing to change\" },\n );\nexport type UpdateSessionRequest = z.infer<typeof UpdateSessionRequest>;\n\n/**\n * `POST /api/sessions/:id/archive`: stop the session if it is running, hide it from the\n * sidebar and remove its worktree. The branch and checkpoints stay.\n */\nexport const ArchiveSessionRequest = z.object({\n /** Remove the worktree even when it has uncommitted changes (those changes are lost). */\n force: z.boolean().default(false),\n});\nexport type ArchiveSessionRequest = z.infer<typeof ArchiveSessionRequest>;\n\n/**\n * What worktree cleanup did: `removed` (`message` notes discarded uncommitted changes);\n * `kept_changes` (uncommitted changes, not forced); `none` (no worktree,\n * or already removed); `failed` (runner unavailable, a file in use; `message` says why).\n */\nexport const WorktreeCleanupOutcome = z.object({\n status: z.enum([\"removed\", \"kept_changes\", \"none\", \"failed\"]),\n message: z.string().nullable(),\n});\nexport type WorktreeCleanupOutcome = z.infer<typeof WorktreeCleanupOutcome>;\n\n/** `POST /api/sessions/:id/archive` response. */\nexport const ArchiveSessionResponse = z.object({\n session: Session,\n worktree: WorktreeCleanupOutcome,\n});\nexport type ArchiveSessionResponse = z.infer<typeof ArchiveSessionResponse>;\n","import { z } from \"zod\";\nimport { ProjectDetection } from \"./api\";\nimport { Project } from \"./entities/project\";\n\n/**\n * Re-detecting a project's git checkout and GitHub remote (§9). A project's kind is first\n * decided when it is added; these shapes cover checking again later, so a folder that gains a\n * git checkout or a GitHub `origin` after it was added catches up.\n */\n\n/**\n * What a re-detection found:\n * - `unchanged`: nothing new (the message says what is still missing, if anything).\n * - `git_detected`: the folder became a git checkout; its default branch is recorded so\n * worktrees work. Still no GitHub remote.\n * - `github_connected`: a local project gained a GitHub `origin` and is now a `github`\n * project, or a GitHub project's missing remote is back.\n * - `github_changed`: the GitHub remote moved (another owner or repository, or another URL).\n * Another repository restarts the issue and PR sync from scratch.\n * - `github_remote_missing`: a GitHub project's folder has no GitHub `origin` any more. The\n * project keeps its coordinates and carries a `remoteWarning`; nothing is downgraded.\n * - `folder_missing`: the project folder is gone or unreadable; nothing was changed.\n */\nexport const ProjectRefreshOutcome = z.enum([\n \"unchanged\",\n \"git_detected\",\n \"github_connected\",\n \"github_changed\",\n \"github_remote_missing\",\n \"folder_missing\",\n]);\nexport type ProjectRefreshOutcome = z.infer<typeof ProjectRefreshOutcome>;\n\n/** `POST /api/projects/:id/refresh` response. */\nexport const RefreshProjectResponse = z.object({\n /** The project after the check (unchanged unless `changed`). */\n project: Project,\n outcome: ProjectRefreshOutcome,\n /** True when the check updated the project (a `project.updated` event was appended). */\n changed: z.boolean(),\n /** One line for the UI, e.g. \"Connected to octo/app\" or \"Still no GitHub remote on origin\". */\n message: z.string(),\n /** What was found in the folder; null when the folder is missing. */\n detected: ProjectDetection.nullable(),\n});\nexport type RefreshProjectResponse = z.infer<typeof RefreshProjectResponse>;\n\n/**\n * `POST /api/projects/:id/disconnect-github` response: the project, now `local`. Allowed only\n * when the folder has no GitHub `origin` (otherwise the next check would connect it again,\n * `409 github_remote_present`) and the project is not in a factory mode (`409 factory_mode`).\n * The synced issues and pull requests stay in the database.\n */\nexport const DisconnectGithubResponse = z.object({ project: Project });\nexport type DisconnectGithubResponse = z.infer<typeof DisconnectGithubResponse>;\n","import { z } from \"zod\";\nimport { AgentEvent } from \"../agent-events\";\nimport { ErrorInfo, Id } from \"../common\";\nimport { BrowserEngine, BrowserFrameMetadata, BrowserTab, BrowserTabId } from \"./browser\";\nimport { CheckpointIndex, PtyId } from \"./commands\";\n\n/**\n * Durable runner -> server events. Journaled by the runner and delivered with a `seq`\n * until the server acknowledges them (§4.2), so nothing is lost while the server is away.\n */\nexport const RunnerEvent = z.discriminatedUnion(\"kind\", [\n /** A normalized agent event for a session. */\n z.object({ kind: z.literal(\"agent\"), sessionId: Id, event: AgentEvent }),\n /** Provider process lifecycle for a session. */\n z.object({\n kind: z.literal(\"session.process\"),\n sessionId: Id,\n state: z.enum([\"starting\", \"ready\", \"exited\", \"crashed\"]),\n exitCode: z.int().nullable().optional(),\n error: ErrorInfo.optional(),\n /**\n * Why an exited session closed: `stopped` (asked to), `runner_exit` (the runner is\n * draining or shutting down; the session stays resumable), `ended` (provider ended it).\n */\n reason: z.enum([\"stopped\", \"runner_exit\", \"ended\"]).optional(),\n /** True when a running turn was cut off by the runner exiting (resume and continue). */\n interruptedTurn: z.boolean().optional(),\n }),\n /** Output of `workspace.prepare` setup commands. */\n z.object({\n kind: z.literal(\"workspace.setup\"),\n sessionId: Id,\n status: z.enum([\"running\", \"succeeded\", \"failed\"]),\n command: z.string(),\n output: z.string().optional(),\n }),\n z.object({ kind: z.literal(\"pty.exited\"), ptyId: PtyId, exitCode: z.int().nullable() }),\n /** A turn checkpoint was written to `refs/codeden/checkpoints/<session>/<index>` (§9). */\n z.object({\n kind: z.literal(\"checkpoint.created\"),\n sessionId: Id,\n index: CheckpointIndex,\n ref: z.string(),\n commit: z.string(),\n /** The turn that ended (absent for the baseline checkpoint 0). */\n turnId: Id.optional(),\n }),\n /** The runner started draining (upgrade/shutdown). */\n z.object({ kind: z.literal(\"runner.draining\"), reason: z.string() }),\n]);\nexport type RunnerEvent = z.infer<typeof RunnerEvent>;\nexport type RunnerEventKind = RunnerEvent[\"kind\"];\n\n/**\n * Ephemeral runner -> server stream data. Not journaled, no `seq`, no ack: dropping it while\n * the server is away is fine (terminals keep scrollback in the runner).\n */\nexport const RunnerStream = z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"pty.output\"), ptyId: PtyId, data: z.string() }),\n z.object({\n kind: z.literal(\"browser.frame\"),\n sessionId: Id,\n mediaType: z.enum([\"image/jpeg\", \"image/png\"]),\n /** Base64 frame data. */\n data: z.string(),\n width: z.int().positive(),\n height: z.int().positive(),\n /** Tab the frame belongs to. */\n tabId: BrowserTabId.optional(),\n /** Viewport geometry at capture time, for mapping panel input onto the page. */\n metadata: BrowserFrameMetadata.optional(),\n }),\n /**\n * The session's tabs changed (opened, closed, activated, navigated, retitled), or its engine\n * did (hand-off to the runner's Chromium). An empty list means the browser closed.\n */\n z.object({\n kind: z.literal(\"browser.tabs\"),\n sessionId: Id,\n tabs: z.array(BrowserTab),\n engine: BrowserEngine.optional(),\n }),\n]);\nexport type RunnerStream = z.infer<typeof RunnerStream>;\n","import { z } from \"zod\";\nimport { ErrorInfo, ProviderId, Timestamp } from \"../common\";\nimport { ProviderInfo } from \"../provider\";\nimport { RunnerCommand, RunnerSessionInfo } from \"./commands\";\nimport { RunnerEvent, RunnerStream } from \"./events\";\n\n/**\n * Server <-> runner protocol over one WebSocket (§4.3).\n *\n * Handshake:\n * 1. server -> `hello` (protocol + server version)\n * 2. runner -> `welcome` (runner id/version/capabilities/providers/sessions) or `reject`\n * 3. server -> `resume` (last seq it has persisted for this runner id)\n * 4. runner replays journaled events with `seq > lastAckedSeq`, then streams live.\n *\n * After the handshake the server sends `command`s (answered by `result` with the same `id`)\n * and cumulative `ack`s; the runner sends `event`s (durable, with `seq`), `stream`s\n * (ephemeral) and `providers` (the current provider list, whenever it changes). Either side\n * may `ping`.\n */\n\n/** Request id correlating a `command` with its `result`. */\nexport const RequestId = z.string().min(1).max(100);\n\n/** Monotonic per-runner event sequence number (distinct from the server's event log seq). */\nexport const RunnerSeq = z.int().positive();\n\n/** Features a runner offers (in addition to provider capabilities). */\nexport const RunnerCapabilities = z.object({\n pty: z.boolean(),\n browser: z.boolean(),\n git: z.boolean(),\n mcpProxy: z.boolean(),\n});\nexport type RunnerCapabilities = z.infer<typeof RunnerCapabilities>;\n\nconst Ping = z.object({ type: z.literal(\"ping\"), id: z.string() });\nconst Pong = z.object({ type: z.literal(\"pong\"), id: z.string() });\n\n// ---------------------------------------------------------------- server -> runner\n\nexport const ServerHello = z.object({\n type: z.literal(\"hello\"),\n protocolVersion: z.int().positive(),\n serverVersion: z.string(),\n});\n\nexport const ServerResume = z.object({\n type: z.literal(\"resume\"),\n /** Highest runner seq the server has durably stored; 0 when none. */\n lastAckedSeq: z.int().nonnegative(),\n});\n\nexport const ServerCommand = z.object({\n type: z.literal(\"command\"),\n id: RequestId,\n command: RunnerCommand,\n});\n\n/** Cumulative ack: every event with `seq <= seq` may be dropped from the journal. */\nexport const ServerAck = z.object({ type: z.literal(\"ack\"), seq: RunnerSeq });\n\nexport const ServerToRunnerMessage = z.discriminatedUnion(\"type\", [\n ServerHello,\n ServerResume,\n ServerCommand,\n ServerAck,\n Ping,\n Pong,\n]);\nexport type ServerToRunnerMessage = z.infer<typeof ServerToRunnerMessage>;\n\n// ---------------------------------------------------------------- runner -> server\n\nexport const RunnerWelcome = z.object({\n type: z.literal(\"welcome\"),\n protocolVersion: z.int().positive(),\n /** Stable id persisted in `<home>/runner/`; survives runner restarts. */\n runnerId: z.string().min(1),\n runnerVersion: z.string(),\n pid: z.int().positive(),\n startedAt: Timestamp,\n capabilities: RunnerCapabilities,\n providers: z.array(ProviderInfo),\n sessions: z.array(RunnerSessionInfo),\n journal: z.object({ lastSeq: z.int().nonnegative(), unacked: z.int().nonnegative() }),\n /** True when the runner is draining and will not accept new sessions. */\n draining: z.boolean(),\n});\nexport type RunnerWelcome = z.infer<typeof RunnerWelcome>;\n\nexport const RunnerReject = z.object({\n type: z.literal(\"reject\"),\n reason: z.enum([\"protocol_mismatch\", \"busy\", \"shutting_down\"]),\n message: z.string(),\n supportedProtocolVersions: z.array(z.int().positive()).optional(),\n});\n\nexport const RunnerResult = z.discriminatedUnion(\"ok\", [\n z.object({ type: z.literal(\"result\"), id: RequestId, ok: z.literal(true), result: z.unknown() }),\n z.object({ type: z.literal(\"result\"), id: RequestId, ok: z.literal(false), error: ErrorInfo }),\n]);\nexport type RunnerResult = z.infer<typeof RunnerResult>;\n\nexport const RunnerEventMessage = z.object({\n type: z.literal(\"event\"),\n seq: RunnerSeq,\n ts: Timestamp,\n event: RunnerEvent,\n});\nexport type RunnerEventMessage = z.infer<typeof RunnerEventMessage>;\n\nexport const RunnerStreamMessage = z.object({\n type: z.literal(\"stream\"),\n ts: Timestamp,\n stream: RunnerStream,\n});\n\n/**\n * The runner's full, current provider list, replacing the one from `welcome`. Sent after\n * `resume` and whenever a provider's models change (model discovery, a session reporting its\n * models). Ephemeral: not journaled, since the next handshake carries the latest list anyway.\n */\nexport const RunnerProvidersMessage = z.object({\n type: z.literal(\"providers\"),\n providers: z.array(ProviderInfo),\n});\nexport type RunnerProvidersMessage = z.infer<typeof RunnerProvidersMessage>;\n\nexport const RunnerToServerMessage = z.discriminatedUnion(\"type\", [\n RunnerWelcome,\n RunnerReject,\n RunnerResult,\n RunnerEventMessage,\n RunnerStreamMessage,\n RunnerProvidersMessage,\n Ping,\n Pong,\n]);\nexport type RunnerToServerMessage = z.infer<typeof RunnerToServerMessage>;\n\n// ---------------------------------------------------------------- lock file\n\n/**\n * `<home>/runner/runner.json`: how the server finds a live runner again (§4.2).\n * Written by the runner once it is listening; removed on clean exit.\n */\nexport const RunnerLock = z.object({\n pid: z.int().positive(),\n port: z.int().min(1).max(65535),\n /** Random token the server must present (`Authorization: Bearer`). */\n token: z.string().min(16),\n version: z.string(),\n protocolVersion: z.int().positive(),\n runnerId: z.string().min(1),\n startedAt: Timestamp,\n providers: z.array(ProviderId).default([]),\n});\nexport type RunnerLock = z.infer<typeof RunnerLock>;\n\n/** `<home>/server.json`: the running server, used by the CLI (`open`, `stop`). */\nexport const ServerLock = z.object({\n pid: z.int().positive(),\n port: z.int().min(1).max(65535),\n version: z.string(),\n startedAt: Timestamp,\n});\nexport type ServerLock = z.infer<typeof ServerLock>;\n","import { z } from \"zod\";\n\n/**\n * Read-only browsing of a session's working directory for the files panel (§12.3).\n * Paths are relative to the session's worktree (or cwd) and use `/` separators.\n */\n\n/** One entry of the session file tree. */\nexport const SessionFileEntry = z.object({\n /** Relative path with `/` separators, e.g. `src/index.ts`. */\n path: z.string().min(1),\n kind: z.enum([\"file\", \"dir\"]),\n sizeBytes: z.int().nonnegative().optional(),\n});\nexport type SessionFileEntry = z.infer<typeof SessionFileEntry>;\n\n/**\n * `GET /api/sessions/:id/files`: every file and folder under the session's working directory,\n * depth-first and sorted (folders first). `.git` and `node_modules` are skipped.\n */\nexport const SessionFileList = z.object({\n /** Absolute working directory the paths are relative to. */\n root: z.string(),\n entries: z.array(SessionFileEntry),\n /** True when the listing was cut off at the entry limit. */\n truncated: z.boolean(),\n});\nexport type SessionFileList = z.infer<typeof SessionFileList>;\n\n/** `GET /api/sessions/:id/files/content` query. */\nexport const SessionFileQuery = z.object({ path: z.string().min(1).max(4096) });\nexport type SessionFileQuery = z.infer<typeof SessionFileQuery>;\n\n/** A text file from the session's working directory. Binary files report `binary: true`. */\nexport const SessionFileContent = z.object({\n path: z.string(),\n content: z.string(),\n sizeBytes: z.int().nonnegative(),\n binary: z.boolean(),\n /** True when only the first part of a large file was returned. */\n truncated: z.boolean(),\n});\nexport type SessionFileContent = z.infer<typeof SessionFileContent>;\n","import { z } from \"zod\";\nimport { Id, Role } from \"./common\";\n\n/**\n * Internal MCP tool definitions (§8.3). One registry is exposed through MCP and also called\n * directly by the UI's API handlers. Only the types live here; the registry is in the server.\n */\n\n/**\n * What a tool's handler is bound to, resolved from the caller's token:\n * - `global`: no project (orchestrator tools).\n * - `project`: the caller's project.\n * - `session`: the caller's own session (and its project).\n */\nexport const ToolScope = z.enum([\"global\", \"project\", \"session\"]);\nexport type ToolScope = z.infer<typeof ToolScope>;\n\n/** Claims encoded in a per-session MCP bearer token; revoked when the session ends. */\nexport const McpTokenClaims = z.object({\n role: Role,\n sessionId: Id,\n projectId: Id.nullable(),\n /** Token id, used for revocation. */\n jti: z.string().min(1),\n});\nexport type McpTokenClaims = z.infer<typeof McpTokenClaims>;\n\n/** Context passed to a tool handler. Narrowed by the tool's scope. */\nexport interface ToolContextBase {\n role: Role;\n /** `mcp` when an agent called it, `ui` when an API handler did. */\n caller: \"mcp\" | \"ui\";\n signal: AbortSignal;\n}\nexport interface GlobalToolContext extends ToolContextBase {\n sessionId: string | null;\n projectId: string | null;\n}\nexport interface ProjectToolContext extends ToolContextBase {\n sessionId: string | null;\n projectId: string;\n}\nexport interface SessionToolContext extends ToolContextBase {\n sessionId: string;\n projectId: string | null;\n}\nexport type ToolContext<S extends ToolScope = ToolScope> = S extends \"session\"\n ? SessionToolContext\n : S extends \"project\"\n ? ProjectToolContext\n : GlobalToolContext;\n\n/** A tool definition. `name` is snake_case and unique across the registry. */\nexport interface ToolDefinition<\n TInput extends z.ZodType = z.ZodType,\n TOutput = unknown,\n S extends ToolScope = ToolScope,\n> {\n name: string;\n /** Shown to agents; write it for a model, not a human. */\n description: string;\n /** Roles that may see and call the tool. Tools outside the caller's role aren't listed. */\n roles: readonly Role[];\n scope: S;\n input: TInput;\n output?: z.ZodType<TOutput>;\n /** Core tools are always loaded; others are deferred behind tool search (§8.3). */\n alwaysLoad?: boolean;\n /** Hidden when the predicate is false (e.g. `generate_image` with no engine). */\n isAvailable?: () => boolean | Promise<boolean>;\n handler: (input: z.output<TInput>, ctx: ToolContext<S>) => Promise<TOutput>;\n}\n\n/** Identity helper that infers a tool's input/output/scope types. */\nexport function defineTool<TInput extends z.ZodType, TOutput, S extends ToolScope>(\n def: ToolDefinition<TInput, TOutput, S>,\n): ToolDefinition<TInput, TOutput, S> {\n return def;\n}\n\n/** Any tool, for registries. */\n// biome-ignore lint/suspicious/noExplicitAny: registries hold heterogeneous tools.\nexport type AnyToolDefinition = ToolDefinition<z.ZodType, any, ToolScope>;\n","import { z } from \"zod\";\nimport { GitHubPrRef, Id, ProviderId, Role, Timestamp } from \"./common\";\n\n/**\n * Usage and cost reports (§12.6). The server keeps a ledger with one row per turn: the\n * turn's own token counts (never a running total) plus who and what the work was for.\n * Costs are labelled honestly: `reported` when the provider returned a USD figure,\n * `estimated` when CodeDen priced the tokens from its price table, `unpriced` when neither.\n */\n\n/** Where a cost figure came from. */\nexport const CostSource = z.enum([\"reported\", \"estimated\", \"unpriced\"]);\nexport type CostSource = z.infer<typeof CostSource>;\n\n/**\n * How a provider is paid for. `subscription` (a claude.ai or ChatGPT login) shows costs as\n * \"API-equivalent\": what the same work would cost on API credits, not a bill.\n */\nexport const BillingMode = z.enum([\"api\", \"subscription\", \"unknown\"]);\nexport type BillingMode = z.infer<typeof BillingMode>;\n\n/** Who started the work a ledger row belongs to. `factory`: software- and dark-factory work. */\nexport const UsageSource = z.enum([\"user\", \"orchestrator\", \"pm\", \"automation\", \"factory\"]);\nexport type UsageSource = z.infer<typeof UsageSource>;\n\n/** Token counts in the four billed categories, plus reasoning (a subset of output). */\nexport const TokenCounts = z.object({\n /** Uncached input tokens (excludes cache reads and writes). */\n inputTokens: z.int().nonnegative(),\n outputTokens: z.int().nonnegative(),\n cacheReadTokens: z.int().nonnegative(),\n cacheWriteTokens: z.int().nonnegative(),\n /** Reasoning/thinking tokens where reported; already counted in `outputTokens`. */\n reasoningTokens: z.int().nonnegative(),\n});\nexport type TokenCounts = z.infer<typeof TokenCounts>;\n\n/** One turn's usage as stored in the ledger. */\nexport const UsageEntry = z.object({\n ...TokenCounts.shape,\n sessionId: Id,\n turnId: Id,\n projectId: Id.nullable(),\n provider: ProviderId,\n model: z.string(),\n role: Role,\n source: UsageSource,\n automationId: Id.nullable(),\n /** USD the provider reported for this turn, when it reports one. */\n reportedCostUsd: z.number().nonnegative().nullable(),\n /** The figure used in reports (reported, else estimated from the price table). */\n costUsd: z.number().nonnegative(),\n costSource: CostSource,\n /** When the turn first reported usage. */\n ts: Timestamp,\n});\nexport type UsageEntry = z.infer<typeof UsageEntry>;\n\n/** Price of a model in USD per million tokens. */\nexport const ModelPrice = z.object({\n provider: ProviderId,\n /** Model id or alias; matched exactly, then as a prefix (`claude-sonnet-4-5` matches dated ids). */\n model: z.string().min(1),\n label: z.string().optional(),\n inputPerMTok: z.number().nonnegative(),\n outputPerMTok: z.number().nonnegative(),\n cacheReadPerMTok: z.number().nonnegative(),\n cacheWritePerMTok: z.number().nonnegative(),\n /** Date the list price was checked (YYYY-MM-DD). */\n asOf: z.iso.date(),\n /** Where the price came from. */\n sourceUrl: z.url().optional(),\n});\nexport type ModelPrice = z.infer<typeof ModelPrice>;\n\n/** A spend alert: daily or monthly, for everything or one project. */\nexport const UsageBudget = z.object({\n id: Id,\n projectId: Id.nullable(),\n period: z.enum([\"daily\", \"monthly\"]),\n limitUsd: z.number().positive(),\n /** Warn once spend reaches this share of the limit (and again when it is exceeded). */\n warnAtPercent: z.int().min(1).max(100).default(80),\n enabled: z.boolean().default(true),\n});\nexport type UsageBudget = z.infer<typeof UsageBudget>;\nexport type UsageBudgetInit = z.input<typeof UsageBudget>;\n\n/** User-editable usage settings (`usage-settings.json` in the data directory). */\nexport const UsageSettings = z.object({\n /** Price overrides and additions; they win over the bundled table for the same model. */\n prices: z.array(ModelPrice).default([]),\n budgets: z.array(UsageBudget).default([]),\n /** Raise an inbox item when a rate-limit window reaches this percentage. */\n rateLimitWarnPercent: z.int().min(1).max(100).default(85),\n /** IANA timezone that days and months are counted in; the machine's when null. */\n timezone: z.string().nullable().default(null),\n});\nexport type UsageSettings = z.infer<typeof UsageSettings>;\nexport type UsageSettingsInit = z.input<typeof UsageSettings>;\n\n/** `GET /api/usage/settings` and `PUT /api/usage/settings`. */\nexport const UsageSettingsResponse = z.object({\n settings: UsageSettings,\n /** The bundled list prices (read-only; override them in `settings.prices`). */\n bundledPrices: z.array(ModelPrice),\n});\nexport type UsageSettingsResponse = z.infer<typeof UsageSettingsResponse>;\n\n/** Range and filters for report queries. Dates are inclusive local days (YYYY-MM-DD). */\nexport const UsageQuery = z.object({\n from: z.iso.date(),\n to: z.iso.date(),\n projectId: Id.optional(),\n provider: ProviderId.optional(),\n model: z.string().optional(),\n role: Role.optional(),\n source: UsageSource.optional(),\n});\nexport type UsageQuery = z.infer<typeof UsageQuery>;\n\n/** Totals over a set of ledger rows. */\nexport const UsageTotals = z.object({\n ...TokenCounts.shape,\n costUsd: z.number().nonnegative(),\n /** Part of `costUsd` that is estimated rather than reported. */\n estimatedCostUsd: z.number().nonnegative(),\n /** Turns whose model has no price and no reported cost. */\n unpricedTurns: z.int().nonnegative(),\n turns: z.int().nonnegative(),\n sessions: z.int().nonnegative(),\n /** Cache reads / (cache reads + cache writes + uncached input); null with no input. */\n cacheHitRate: z.number().min(0).max(1).nullable(),\n});\nexport type UsageTotals = z.infer<typeof UsageTotals>;\n\n/** Dimensions reports break down by. */\nexport const UsageDimension = z.enum([\"provider\", \"model\", \"project\", \"role\", \"source\"]);\nexport type UsageDimension = z.infer<typeof UsageDimension>;\n\n/** One value of a dimension with its daily cost and tokens (aligned with `UsageReport.days`). */\nexport const UsageSeries = z.object({\n key: z.string(),\n label: z.string(),\n costUsd: z.number().nonnegative(),\n estimatedCostUsd: z.number().nonnegative(),\n tokens: z.int().nonnegative(),\n turns: z.int().nonnegative(),\n sessions: z.int().nonnegative(),\n dailyCostUsd: z.array(z.number().nonnegative()),\n dailyTokens: z.array(z.int().nonnegative()),\n});\nexport type UsageSeries = z.infer<typeof UsageSeries>;\n\n/** A session ranked by cost. */\nexport const UsageSessionRow = z.object({\n sessionId: Id,\n title: z.string(),\n projectId: Id.nullable(),\n projectName: z.string().nullable(),\n provider: ProviderId,\n model: z.string(),\n role: Role,\n source: UsageSource,\n costUsd: z.number().nonnegative(),\n estimated: z.boolean(),\n tokens: z.int().nonnegative(),\n turns: z.int().nonnegative(),\n lastAt: Timestamp,\n pr: GitHubPrRef.nullable(),\n});\nexport type UsageSessionRow = z.infer<typeof UsageSessionRow>;\n\n/** Spend of one automation. */\nexport const AutomationSpend = z.object({\n automationId: Id,\n name: z.string(),\n costUsd: z.number().nonnegative(),\n sessions: z.int().nonnegative(),\n});\nexport type AutomationSpend = z.infer<typeof AutomationSpend>;\n\n/** `GET /api/usage/report`. */\nexport const UsageReport = z.object({\n query: UsageQuery,\n timezone: z.string(),\n /** Local days in the range, oldest first. */\n days: z.array(z.iso.date()),\n totals: UsageTotals,\n /** The same totals for the equally long range just before (for trend arrows). */\n previousTotals: UsageTotals,\n series: z.record(UsageDimension, z.array(UsageSeries)),\n topSessions: z.array(UsageSessionRow),\n automations: z.object({\n manualCostUsd: z.number().nonnegative(),\n automationCostUsd: z.number().nonnegative(),\n factoryCostUsd: z.number().nonnegative(),\n byAutomation: z.array(AutomationSpend),\n }),\n averages: z.object({\n perSessionUsd: z.number().nonnegative().nullable(),\n /** Spend of sessions whose PR merged, divided by the merged PRs (null with none). */\n perMergedPrUsd: z.number().nonnegative().nullable(),\n mergedPrs: z.int().nonnegative(),\n }),\n /** How each provider in the range is billed, for the \"API-equivalent\" label. */\n billing: z.record(ProviderId, BillingMode),\n});\nexport type UsageReport = z.infer<typeof UsageReport>;\n\n/** One turn's usage for the turn footer. */\nexport const TurnUsage = z.object({\n ...TokenCounts.shape,\n turnId: Id,\n costUsd: z.number().nonnegative(),\n costSource: CostSource,\n});\nexport type TurnUsage = z.infer<typeof TurnUsage>;\n\n/** `GET /api/usage/sessions/:id`: totals for the session header plus per-turn rows. */\nexport const SessionUsage = z.object({\n sessionId: Id,\n totals: UsageTotals,\n billing: BillingMode,\n turns: z.array(TurnUsage),\n});\nexport type SessionUsage = z.infer<typeof SessionUsage>;\n\n/** A provider rate-limit window as last reported. */\nexport const RateLimitWindow = z.object({\n provider: ProviderId,\n /** Window id from the provider: `5h`, `weekly`, `weekly-opus`, ... */\n windowId: z.string(),\n label: z.string(),\n status: z.enum([\"ok\", \"warning\", \"limited\"]),\n usedPercent: z.number().min(0).max(100).nullable(),\n resetsAt: Timestamp.nullable(),\n observedAt: Timestamp,\n /** The window has reset since this reading, so the percentage is out of date. */\n stale: z.boolean(),\n});\nexport type RateLimitWindow = z.infer<typeof RateLimitWindow>;\n\n/** `GET /api/usage/limits`. */\nexport const RateLimitsResponse = z.object({\n windows: z.array(RateLimitWindow),\n warnPercent: z.int(),\n billing: z.record(ProviderId, BillingMode),\n});\nexport type RateLimitsResponse = z.infer<typeof RateLimitsResponse>;\n\n/** Where a budget stands in its current period. */\nexport const BudgetStatus = z.object({\n budget: UsageBudget,\n periodStart: z.iso.date(),\n spentUsd: z.number().nonnegative(),\n percent: z.number().nonnegative(),\n state: z.enum([\"ok\", \"warning\", \"exceeded\"]),\n});\nexport type BudgetStatus = z.infer<typeof BudgetStatus>;\n\n/** `GET /api/usage/budgets`. */\nexport const BudgetsResponse = z.object({ budgets: z.array(BudgetStatus) });\nexport type BudgetsResponse = z.infer<typeof BudgetsResponse>;\n\n/** `GET /api/usage/projects/:id`: the project home spend card. */\nexport const ProjectSpend = z.object({\n projectId: Id,\n todayUsd: z.number().nonnegative(),\n last7Usd: z.number().nonnegative(),\n monthUsd: z.number().nonnegative(),\n estimated: z.boolean(),\n /** Last 14 local days, oldest first. */\n dailyUsd: z.array(z.number().nonnegative()),\n topModel: z.string().nullable(),\n budgets: z.array(BudgetStatus),\n billing: z.record(ProviderId, BillingMode),\n});\nexport type ProjectSpend = z.infer<typeof ProjectSpend>;\n","/**\n * The version written into the source; kept in sync with `apps/cli/package.json` and\n * `apps/desktop/package.json` (tested).\n */\nexport const SOURCE_VERSION = \"0.6.2\";\n\n/**\n * CodeDen release version. Server and runner exchange it during the runner handshake to detect\n * upgrades. The published entries (`dist/cli.js`, `dist/runner.js`) set\n * `globalThis.__CODEDEN_PACKAGE_VERSION__` from their own `package.json` before loading the\n * rest of the bundle, so the package version is the single source of truth at runtime;\n * everywhere else (workspace, tests) it is `SOURCE_VERSION`.\n */\nexport const CODEDEN_VERSION: string = packageVersion() ?? SOURCE_VERSION;\n\nfunction packageVersion(): string | undefined {\n const value = (globalThis as { __CODEDEN_PACKAGE_VERSION__?: unknown })\n .__CODEDEN_PACKAGE_VERSION__;\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/** Version of the server <-> runner WebSocket protocol (§4.3). Bump on breaking changes. */\nexport const RUNNER_PROTOCOL_VERSION = 1;\n\n/** Version of the server <-> UI WebSocket protocol. Bump on breaking changes. */\nexport const UI_PROTOCOL_VERSION = 1;\n","/** Names of CodeDen-internal variables that must never reach agents, shells or setup scripts. */\nconst SECRET = /^CODEDEN_.*(TOKEN|SECRET|KEY|PASSWORD)/i;\n\n/**\n * Set when the desktop app runs CodeDen's own processes on its Electron binary (§17). It must\n * not reach the user's shells and agents: an Electron app started there would run as Node.js.\n */\nconst RUNTIME_ONLY = new Set([\"ELECTRON_RUN_AS_NODE\"]);\n\n/**\n * Environment for child processes (§15): the user's environment minus CodeDen's own\n * secrets. `CODEDEN_HOME` and similar non-secret variables are kept.\n */\nexport function childEnv(extra: Record<string, string> = {}): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(process.env)) {\n if (value === undefined || SECRET.test(key) || RUNTIME_ONLY.has(key)) continue;\n out[key] = value;\n }\n return { ...out, ...extra };\n}\n","import { execFile } from \"node:child_process\";\n\nconst isWindows = process.platform === \"win32\";\n\nfunction exec(file: string, args: string[], timeoutMs = 15_000): Promise<string> {\n return new Promise((resolve, reject) => {\n execFile(\n file,\n args,\n { windowsHide: true, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 },\n (error, stdout) => (error ? reject(error) : resolve(stdout)),\n );\n });\n}\n\n/** True when a process with this pid exists (EPERM still means it exists). */\nexport function isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/**\n * Kill a process and everything it started.\n * - Windows: `taskkill /T /F /PID <pid>` (walks the parent-pid tree).\n * - POSIX: signal the process group (children are spawned as group leaders), then the pid.\n * `SIGTERM` first; `SIGKILL` after `graceMs` if anything is still alive.\n */\nexport async function killTree(pid: number, graceMs = 2_000): Promise<void> {\n if (!isAlive(pid)) return;\n if (isWindows) {\n await exec(\"taskkill\", [\"/T\", \"/F\", \"/PID\", String(pid)]).catch(() => undefined);\n return;\n }\n const descendants = await listDescendants(pid).catch(() => [] as number[]);\n signalPosix(pid, descendants, \"SIGTERM\");\n const deadline = Date.now() + graceMs;\n while (Date.now() < deadline) {\n if (![pid, ...descendants].some(isAlive)) return;\n await new Promise((r) => setTimeout(r, 50));\n }\n signalPosix(pid, descendants, \"SIGKILL\");\n}\n\n/**\n * Kill a process and everything it started, also when it has already exited. Its\n * descendants are listed first and killed as trees of their own: on Windows the children of\n * an exited process keep its pid as their parent id, so they are still found. On POSIX, where\n * such children are adopted by init, the process must have been spawned as a process-group\n * leader (`detached`): its group is signalled, which outlives the leader. (A descendant that\n * started a session of its own after its parent exited can't be found there.)\n */\nexport async function killTreeAndOrphans(\n pid: number,\n graceMs = 2_000,\n ops: TreeOps = systemTreeOps,\n): Promise<void> {\n const descendants = await ops.listDescendants(pid).catch(() => [] as number[]);\n await ops.killTree(pid, graceMs);\n await Promise.all(descendants.map((child) => ops.killTree(child, graceMs)));\n if (ops.platform !== \"win32\") ops.killGroup(pid);\n}\n\n/** What `killTreeAndOrphans` does to processes; tests pass fakes. */\nexport interface TreeOps {\n platform: NodeJS.Platform;\n listDescendants: (pid: number) => Promise<number[]>;\n killTree: (pid: number, graceMs: number) => Promise<void>;\n /** `SIGKILL` the process group led by `pid`, if it still exists. */\n killGroup: (pid: number) => void;\n}\n\nconst systemTreeOps: TreeOps = {\n platform: process.platform,\n listDescendants: (pid) => listDescendants(pid),\n killTree: (pid, graceMs) => killTree(pid, graceMs),\n killGroup: (pid) => {\n try {\n process.kill(-pid, \"SIGKILL\");\n } catch {\n // the group is gone\n }\n },\n};\n\nfunction signalPosix(pid: number, descendants: number[], signal: NodeJS.Signals): void {\n for (const target of [-pid, pid, ...descendants]) {\n try {\n process.kill(target, signal);\n } catch {\n // gone, or not a group leader\n }\n }\n}\n\n/** Parse `pid ppid` lines into a parent -> children map. */\nexport function parseProcessTable(output: string): Map<number, number[]> {\n const children = new Map<number, number[]>();\n for (const line of output.split(/\\r?\\n/)) {\n const match = /^\\s*(\\d+)\\s+(\\d+)\\s*$/.exec(line);\n if (!match) continue;\n const pid = Number(match[1]);\n const ppid = Number(match[2]);\n if (pid === ppid) continue;\n const list = children.get(ppid) ?? [];\n list.push(pid);\n children.set(ppid, list);\n }\n return children;\n}\n\nasync function processTable(): Promise<Map<number, number[]>> {\n const output = isWindows\n ? await exec(\"powershell.exe\", [\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-Command\",\n 'Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.ParentProcessId)\" }',\n ])\n : await exec(\"ps\", [\"-A\", \"-o\", \"pid=,ppid=\"]);\n return parseProcessTable(output);\n}\n\n/** All descendants of `rootPid` (children, grandchildren, ...), breadth first. */\nexport async function listDescendants(rootPid: number): Promise<number[]> {\n const table = await processTable();\n const out: number[] = [];\n const seen = new Set<number>([rootPid]);\n const queue = [rootPid];\n while (queue.length > 0) {\n const pid = queue.shift() as number;\n for (const child of table.get(pid) ?? []) {\n if (seen.has(child)) continue;\n seen.add(child);\n out.push(child);\n queue.push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